coverage-report

Code coverage report for All files

npmtest-sinopia (v0.0.1)

Code coverage report for All files

Statements: 19.41% (4915 / 25322)      Branches: 5.52% (808 / 14631)      Functions: 7.64% (248 / 3244)      Lines: 19.99% (4896 / 24494)      Ignored: 58 statements, 7 functions, 67 branches     

File Statements Branches Functions Lines
node-npmtest-sinopia/ 100% (147 / 147) 100% (122 / 122) 100% (26 / 26) 100% (147 / 147)
node-npmtest-sinopia/sinopia/ 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
node-npmtest-sinopia/sinopia/lib/ 15.2% (271 / 1783) 0.11% (1 / 921) 1.18% (4 / 339) 16.3% (271 / 1663)
node-npmtest-sinopia/sinopia/node_modules/JSONStream/ 4.44% (6 / 135) 2.33% (2 / 86) 0% (0 / 15) 4.88% (6 / 123)
node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/jsonparse/ 13.46% (56 / 416) 0% (0 / 283) 0% (0 / 12) 16.67% (56 / 336)
node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/through/ 8.45% (6 / 71) 0% (0 / 34) 0% (0 / 13) 9.52% (6 / 63)
node-npmtest-sinopia/sinopia/node_modules/async/lib/ 15.59% (97 / 622) 3.42% (9 / 263) 1.97% (4 / 203) 15.75% (97 / 616)
node-npmtest-sinopia/sinopia/node_modules/bunyan/lib/ 16.94% (104 / 614) 1.81% (6 / 332) 4.62% (3 / 65) 17.08% (104 / 609)
node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/dtrace-provider/ 62.5% (15 / 24) 55.56% (5 / 9) 0% (0 / 7) 62.5% (15 / 24)
node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/ 17.81% (13 / 73) 0% (0 / 34) 0% (0 / 14) 19.12% (13 / 68)
node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/ncp/lib/ 14.62% (19 / 130) 0% (0 / 85) 0% (0 / 31) 14.84% (19 / 128)
node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/rimraf/ 12.67% (19 / 150) 0% (0 / 95) 0% (0 / 22) 12.84% (19 / 148)
node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/safe-json-stringify/ 23.33% (7 / 30) 0% (0 / 14) 0% (0 / 6) 23.33% (7 / 30)
node-npmtest-sinopia/sinopia/node_modules/compression/ 14.42% (15 / 104) 0% (0 / 62) 0% (0 / 16) 14.42% (15 / 104)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/ 20.37% (11 / 54) 0% (0 / 34) 0% (0 / 7) 26.83% (11 / 41)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/ 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/ 60.53% (23 / 38) 0% (0 / 10) 0% (0 / 9) 60.53% (23 / 38)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/ 15.32% (38 / 248) 0% (0 / 155) 0% (0 / 45) 15.77% (38 / 241)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/bytes/ 11.76% (2 / 17) 0% (0 / 10) 0% (0 / 2) 16.67% (2 / 12)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/ 27.27% (3 / 11) 0% (0 / 8) 0% (0 / 1) 33.33% (3 / 9)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/node_modules/mime-db/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/ 40.14% (57 / 142) 14.71% (10 / 68) 27.78% (5 / 18) 40.88% (56 / 137)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node_modules/ms/ 22.73% (10 / 44) 0% (0 / 57) 0% (0 / 5) 28.57% (10 / 35)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/on-headers/ 11.11% (4 / 36) 0% (0 / 22) 0% (0 / 4) 11.43% (4 / 35)
node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/vary/ 19.35% (6 / 31) 0% (0 / 27) 0% (0 / 3) 19.35% (6 / 31)
node-npmtest-sinopia/sinopia/node_modules/es6-shim/ 22.3% (264 / 1184) 13.71% (96 / 700) 22.7% (42 / 185) 23.15% (256 / 1106)
node-npmtest-sinopia/sinopia/node_modules/express/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/express/lib/ 20.82% (157 / 754) 0% (0 / 354) 2.97% (3 / 101) 22.11% (157 / 710)
node-npmtest-sinopia/sinopia/node_modules/express/lib/router/ 13.37% (50 / 374) 0% (0 / 188) 5% (2 / 40) 13.55% (50 / 369)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/ 20.37% (11 / 54) 0% (0 / 34) 0% (0 / 7) 26.83% (11 / 41)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/ 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/ 16.6% (40 / 241) 0% (0 / 152) 2.74% (2 / 73) 17.24% (40 / 232)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/content-disposition/ 20.66% (25 / 121) 0% (0 / 75) 0% (0 / 11) 20.66% (25 / 121)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie-signature/ 25% (4 / 16) 0% (0 / 10) 0% (0 / 3) 33.33% (4 / 12)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie/ 14.29% (6 / 42) 0% (0 / 28) 0% (0 / 3) 16.67% (6 / 36)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/ 40.14% (57 / 142) 14.71% (10 / 68) 27.78% (5 / 18) 40.88% (56 / 137)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node_modules/ms/ 24.39% (10 / 41) 0% (0 / 55) 0% (0 / 5) 30.3% (10 / 33)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/ 39.34% (83 / 211) 15.79% (15 / 95) 38.46% (10 / 26) 39.42% (82 / 208)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/lib/compat/ 91.3% (21 / 23) 25% (1 / 4) 66.67% (4 / 6) 91.3% (21 / 23)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/escape-html/ 50% (1 / 2) 100% (0 / 0) 0% (0 / 1) 50% (1 / 2)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/ 28.57% (12 / 42) 0% (0 / 42) 0% (0 / 5) 28.57% (12 / 42)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/ 47.66% (61 / 128) 18.42% (7 / 38) 10% (1 / 10) 47.66% (61 / 128)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/finalhandler/ 37.29% (22 / 59) 19.51% (8 / 41) 33.33% (2 / 6) 37.29% (22 / 59)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/fresh/ 9.09% (2 / 22) 0% (0 / 18) 0% (0 / 1) 11.11% (2 / 18)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/media-typer/ 17.05% (15 / 88) 0% (0 / 54) 0% (0 / 5) 17.05% (15 / 88)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/merge-descriptors/ 20% (1 / 5) 100% (0 / 0) 0% (0 / 2) 20% (1 / 5)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/methods/ 80% (4 / 5) 50% (1 / 2) 100% (1 / 1) 80% (4 / 5)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/ 21.21% (14 / 66) 6.25% (2 / 32) 9.09% (1 / 11) 22.95% (14 / 61)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/node_modules/ee-first/ 14.71% (5 / 34) 0% (0 / 8) 0% (0 / 6) 14.71% (5 / 34)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/parseurl/ 24.39% (10 / 41) 0% (0 / 23) 0% (0 / 4) 24.39% (10 / 41)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/path-to-regexp/ 9.09% (2 / 22) 0% (0 / 32) 0% (0 / 3) 9.09% (2 / 22)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/ 14.18% (19 / 134) 0% (0 / 72) 0% (0 / 12) 14.62% (19 / 130)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/ 25% (2 / 8) 0% (0 / 4) 0% (0 / 1) 25% (2 / 8)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ 21.59% (57 / 264) 12.63% (12 / 95) 12.82% (5 / 39) 21.59% (57 / 264)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/ 13.04% (21 / 161) 0% (0 / 115) 0% (0 / 12) 13.04% (21 / 161)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/range-parser/ 5.26% (1 / 19) 0% (0 / 16) 0% (0 / 2) 5.88% (1 / 17)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/ 16.83% (51 / 303) 1.22% (2 / 164) 2.63% (1 / 38) 18.09% (51 / 282)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/destroy/ 27.78% (5 / 18) 0% (0 / 10) 0% (0 / 3) 27.78% (5 / 18)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/mime/ 88.89% (32 / 36) 45.45% (5 / 11) 71.43% (5 / 7) 88.89% (32 / 36)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/ms/ 24.39% (10 / 41) 0% (0 / 43) 0% (0 / 5) 30.3% (10 / 33)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/serve-static/ 17.31% (9 / 52) 0% (0 / 31) 0% (0 / 5) 17.31% (9 / 52)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/ 18.84% (13 / 69) 0% (0 / 50) 0% (0 / 6) 19.4% (13 / 67)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/ 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/utils-merge/ 20% (1 / 5) 0% (0 / 4) 0% (0 / 1) 20% (1 / 5)
node-npmtest-sinopia/sinopia/node_modules/express/node_modules/vary/ 19.35% (6 / 31) 0% (0 / 27) 0% (0 / 3) 19.35% (6 / 31)
node-npmtest-sinopia/sinopia/node_modules/http-errors/ 38.46% (25 / 65) 11.76% (4 / 34) 57.14% (4 / 7) 38.46% (25 / 65)
node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/inherits/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/statuses/ 44.44% (12 / 27) 0% (0 / 12) 50% (1 / 2) 50% (12 / 24)
node-npmtest-sinopia/sinopia/node_modules/jju/ 50% (6 / 12) 100% (0 / 0) 0% (0 / 6) 50% (6 / 12)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/ 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/ 96.15% (25 / 26) 100% (0 / 0) 50% (1 / 2) 96.15% (25 / 26)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/ 39.21% (545 / 1390) 29.57% (293 / 991) 45.74% (43 / 94) 39.52% (545 / 1379)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/ 100% (10 / 10) 100% (0 / 0) 100% (0 / 0) 100% (10 / 10)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/ 26.5% (97 / 366) 15.45% (34 / 220) 16.67% (8 / 48) 27.4% (97 / 354)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/ 27.63% (21 / 76) 0% (0 / 38) 0% (0 / 13) 28.77% (21 / 73)
node-npmtest-sinopia/sinopia/node_modules/js-yaml/node_modules/esprima/ 7.55% (205 / 2714) 1.98% (31 / 1567) 1.8% (4 / 222) 7.55% (205 / 2714)
node-npmtest-sinopia/sinopia/node_modules/lunr/ 27.18% (153 / 563) 6.67% (14 / 210) 21.65% (21 / 97) 29.49% (151 / 512)
node-npmtest-sinopia/sinopia/node_modules/minimatch/ 8.77% (42 / 479) 1.64% (5 / 305) 6.38% (3 / 47) 9.23% (41 / 444)
node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/lru-cache/lib/ 25.82% (47 / 182) 17.76% (19 / 107) 10.34% (3 / 29) 28.48% (47 / 165)
node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/sigmund/ 10.71% (3 / 28) 0% (0 / 23) 0% (0 / 3) 12.5% (3 / 24)
node-npmtest-sinopia/sinopia/node_modules/mkdirp/ 10.34% (6 / 58) 0% (0 / 42) 0% (0 / 6) 11.32% (6 / 53)
node-npmtest-sinopia/sinopia/node_modules/readable-stream/ 100% (7 / 7) 100% (0 / 0) 100% (0 / 0) 100% (7 / 7)
node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/ 14.8% (123 / 831) 1.41% (7 / 497) 1.96% (2 / 102) 14.89% (123 / 826)
node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/core-util-is/lib/ 65.96% (31 / 47) 0% (0 / 15) 0% (0 / 16) 65.96% (31 / 47)
node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/inherits/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/isarray/ 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
node-npmtest-sinopia/sinopia/node_modules/request/ 8.25% (73 / 885) 0.47% (3 / 645) 1.18% (1 / 85) 8.3% (73 / 879)
node-npmtest-sinopia/sinopia/node_modules/request/lib/ 16.6% (82 / 494) 0.27% (1 / 365) 5% (3 / 60) 16.73% (82 / 490)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/aws-sign2/ 42.22% (19 / 45) 0% (0 / 14) 0% (0 / 9) 45.24% (19 / 42)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/ 18.42% (21 / 114) 0% (0 / 61) 10% (2 / 20) 18.42% (21 / 114)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/ 13.77% (96 / 697) 0.93% (4 / 430) 2.3% (2 / 87) 13.89% (96 / 691)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/ 65.96% (31 / 47) 0% (0 / 15) 0% (0 / 16) 65.96% (31 / 47)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/ 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/caseless/ 15.69% (8 / 51) 0% (0 / 20) 0% (0 / 13) 17.78% (8 / 45)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/lib/ 19.64% (22 / 112) 0% (0 / 43) 0% (0 / 20) 20% (22 / 110)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/ 22.95% (14 / 61) 0% (0 / 14) 0% (0 / 13) 22.95% (14 / 61)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/forever-agent/ 19.75% (16 / 81) 0% (0 / 53) 0% (0 / 8) 20% (16 / 80)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/lib/ 17.65% (27 / 153) 0% (0 / 84) 0% (0 / 22) 18% (27 / 150)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/ 19.64% (22 / 112) 0% (0 / 43) 0% (0 / 20) 20% (22 / 110)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/ 22.03% (13 / 59) 0% (0 / 14) 0% (0 / 12) 22.03% (13 / 59)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/ 8.77% (35 / 399) 0% (0 / 237) 0% (0 / 44) 9.83% (35 / 356)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/ 9.76% (4 / 41) 0% (0 / 14) 0% (0 / 7) 10.53% (4 / 38)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/ 71.43% (5 / 7) 0% (0 / 4) 0% (0 / 2) 71.43% (5 / 7)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/ 66.67% (2 / 3) 100% (0 / 0) 0% (0 / 1) 66.67% (2 / 3)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/ 17.78% (8 / 45) 0% (0 / 22) 0% (0 / 6) 17.78% (8 / 45)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/ 22.22% (2 / 9) 0% (0 / 2) 0% (0 / 1) 22.22% (2 / 9)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/ 45.45% (10 / 22) 0% (0 / 6) 20% (1 / 5) 45.45% (10 / 22)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/schemas/ 100% (21 / 21) 100% (0 / 0) 100% (0 / 0) 100% (21 / 21)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/ 15.74% (54 / 343) 0% (0 / 326) 0% (0 / 33) 15.84% (54 / 341)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/lib/ 27.59% (32 / 116) 0% (0 / 50) 0% (0 / 29) 27.59% (32 / 116)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/ 22.22% (6 / 27) 0% (0 / 14) 0% (0 / 3) 22.22% (6 / 27)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/ 13.52% (66 / 488) 3.82% (13 / 340) 1.69% (1 / 59) 13.52% (66 / 488)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/lib/ 9.09% (16 / 176) 0% (0 / 83) 0% (0 / 22) 9.64% (16 / 166)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/ 11.86% (46 / 388) 0% (0 / 135) 0% (0 / 23) 12.07% (46 / 381)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/ 14.61% (52 / 356) 1.29% (2 / 155) 0% (0 / 38) 14.69% (52 / 354)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/assert-plus/ 55.43% (51 / 92) 26.23% (16 / 61) 20.83% (5 / 24) 55.43% (51 / 92)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ 12.75% (138 / 1082) 0% (0 / 580) 0% (0 / 83) 12.77% (138 / 1081)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/isstream/ 69.23% (9 / 13) 0% (0 / 8) 0% (0 / 4) 69.23% (9 / 13)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/json-stringify-safe/ 20% (4 / 20) 0% (0 / 14) 0% (0 / 4) 23.53% (4 / 17)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/ 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/node_modules/mime-db/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/node-uuid/ 33.02% (35 / 106) 14.29% (11 / 77) 18.18% (2 / 11) 33.01% (34 / 103)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/oauth-sign/ 28.07% (16 / 57) 0% (0 / 28) 0% (0 / 13) 28.07% (16 / 57)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/ 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/ 11.52% (25 / 217) 1.23% (2 / 163) 0% (0 / 16) 11.52% (25 / 217)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/stringstream/ 22.08% (17 / 77) 0% (0 / 35) 0% (0 / 10) 25% (17 / 68)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/ 20.16% (126 / 625) 0.71% (3 / 423) 8.96% (6 / 67) 20.29% (126 / 621)
node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tunnel-agent/ 19.4% (26 / 134) 5.88% (2 / 34) 0% (0 / 23) 19.55% (26 / 133)
node-npmtest-sinopia/sinopia/node_modules/semver/ 27.65% (185 / 669) 3.26% (12 / 368) 1.23% (1 / 81) 28.07% (185 / 659)
Code coverage report for node-npmtest-sinopia/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/

Statements: 100% (147 / 147)      Branches: 100% (122 / 122)      Functions: 100% (26 / 26)      Lines: 100% (147 / 147)      Ignored: 26 statements, 1 function, 30 branches     

All files » node-npmtest-sinopia/
File Statements Branches Functions Lines
example.js 100% (83 / 83) 100% (73 / 73) 100% (12 / 12) 100% (83 / 83)
lib.npmtest_sinopia.js 100% (16 / 16) 100% (14 / 14) 100% (3 / 3) 100% (16 / 16)
test.js 100% (48 / 48) 100% (35 / 35) 100% (11 / 11) 100% (48 / 48)
Code coverage report for node-npmtest-sinopia/example.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/example.js

Statements: 100% (83 / 83)      Branches: 100% (73 / 73)      Functions: 100% (12 / 12)      Lines: 100% (83 / 83)      Ignored: 26 statements, 1 function, 30 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327                                                  2   2         2   2   2 2 2         1             2       2       2   2               1 2           2     2     2 2   1       2     1 1 1   1 1     1 1   1     1   2           1   1   1         1 2 2 2 2 2 2 1     2 2         2       1 3 1       1 1               1   1 1 1   1   1                                                                                                                                                                                       1 1                       1     6 6   1   2   1   2         1 1   1     1               1     1 1     1 1   1 1 1 1 1 1 1   1 1   1        
/*
example.js
 
quickstart example
 
instruction
    1. save this script as example.js
    2. run the shell command:
        $ npm install npmtest-sinopia && PORT=8081 node example.js
    3. play with the browser-demo on http://127.0.0.1:8081
*/
 
 
 
/* istanbul instrument in package npmtest_sinopia */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || (local.modeJs === 'browser'
            ? local.global.utility2_npmtest_sinopia
            : global.utility2_moduleExports);
        // export local
        local.global.local = local;
    }());
    switch (local.modeJs) {
 
 
 
    // post-init
    // run browser js-env code - post-init
    /* istanbul ignore next */
    case 'browser':
        local.testRunBrowser = function (event) {
            Eif (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('onreset'))) {
                // reset output
                Array.from(
                    document.querySelectorAll('body > .resettable')
                ).forEach(function (element) {
                    switch (element.tagName) {
                    case 'INPUT':
                    case 'TEXTAREA':
                        element.value = '';
                        break;
                    default:
                        element.textContent = '';
                    }
                });
            }
            switch (event && event.currentTarget && event.currentTarget.id) {
            case 'testRunButton1':
                // show tests
                Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
                    document.querySelector('#testReportDiv1').style.display = 'block';
                    document.querySelector('#testRunButton1').textContent =
                        'hide internal test';
                    local.modeTest = true;
                    local.testRunDefault(local);
                // hide tests
                } else {
                    document.querySelector('#testReportDiv1').style.display = 'none';
                    document.querySelector('#testRunButton1').textContent = 'run internal test';
                }
                break;
            // custom-case
            default:
                break;
            }
            Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
                    event.currentTarget &&
                    event.currentTarget.className &&
                    event.currentTarget.className.includes &&
                    event.currentTarget.className.includes('oneval')))) {
                // try to eval input-code
                try {
                    /*jslint evil: true*/
                    eval(document.querySelector('#inputTextareaEval1').value);
                } catch (errorCaught) {
                    console.error(errorCaught.stack);
                }
            }
        };
        // log stderr and stdout to #outputTextareaStdout1
        ['error', 'log'].forEach(function (key) {
            console[key + '_original'] = console[key];
            console[key] = function () {
                var element;
                console[key + '_original'].apply(console, arguments);
                element = document.querySelector('#outputTextareaStdout1');
                Iif (!element) {
                    return;
                }
                // append text to #outputTextareaStdout1
                element.value += Array.from(arguments).map(function (arg) {
                    return typeof arg === 'string'
                        ? arg
                        : JSON.stringify(arg, null, 4);
                }).join(' ') + '\n';
                // scroll textarea to bottom
                element.scrollTop = element.scrollHeight;
            };
        });
        // init event-handling
        ['change', 'click', 'keyup'].forEach(function (event) {
            Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
                element.addEventListener(event, local.testRunBrowser);
            });
        });
        // run tests
        local.testRunBrowser();
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        // export local
        module.exports = local;
        // require modules
        local.fs = require('fs');
        local.http = require('http');
        local.url = require('url');
        // init assets
        local.assetsDict = local.assetsDict || {};
        /* jslint-ignore-begin */
        local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
    box-sizing: false,\n\
    universal-selector: false\n\
*/\n\
* {\n\
    box-sizing: border-box;\n\
}\n\
body {\n\
    background: #dde;\n\
    font-family: Arial, Helvetica, sans-serif;\n\
    margin: 2rem;\n\
}\n\
body > * {\n\
    margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
    margin-top: 20px;\n\
    text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
    font-family: monospace;\n\
    height: 10rem;\n\
    width: 100%;\n\
}\n\
textarea[readonly] {\n\
    background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
    <a\n\
        {{#if env.npm_package_homepage}}\n\
        href="{{env.npm_package_homepage}}"\n\
        {{/if env.npm_package_homepage}}\n\
        target="_blank"\n\
    >\n\
utility2-comment -->\n\
        {{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
    </a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_sinopia.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
    [ this app was created with\n\
    <a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
    ]\n\
</div>\n\
</body>\n\
</html>\n\
';
        /* jslint-ignore-end */
        Iif (local.templateRender) {
            local.assetsDict['/'] = local.templateRender(
                local.assetsDict['/assets.index.template.html'],
                {
                    env: local.objectSetDefault(local.env, {
                        npm_package_description: 'the greatest app in the world!',
                        npm_package_name: 'my-app',
                        npm_package_nameAlias: 'my_app',
                        npm_package_version: '0.0.1'
                    })
                }
            );
        } else {
            local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
                .replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
                    // jslint-hack
                    String(match0);
                    switch (match1) {
                    case 'npm_package_description':
                        return 'the greatest app in the world!';
                    case 'npm_package_name':
                        return 'my-app';
                    case 'npm_package_nameAlias':
                        return 'my_app';
                    case 'npm_package_version':
                        return '0.0.1';
                    }
                });
        }
        // run the cli
        Eif (local.global.utility2_rollup || module !== require.main) {
            break;
        }
        local.assetsDict['/assets.example.js'] =
            local.assetsDict['/assets.example.js'] ||
            local.fs.readFileSync(__filename, 'utf8');
        local.assetsDict['/assets.npmtest_sinopia.rollup.js'] =
            local.assetsDict['/assets.npmtest_sinopia.rollup.js'] ||
            local.fs.readFileSync(
                // buildCustomOrg-hack
                local.npmtest_sinopia.__dirname +
                    '/lib.npmtest_sinopia.js',
                'utf8'
            ).replace((/^#!/), '//');
        local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
        // if $npm_config_timeout_exit exists,
        // then exit this process after $npm_config_timeout_exit ms
        if (Number(process.env.npm_config_timeout_exit)) {
            setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
        }
        // start server
        if (local.global.utility2_serverHttp1) {
            break;
        }
        process.env.PORT = process.env.PORT || '8081';
        console.error('server starting on port ' + process.env.PORT);
        local.http.createServer(function (request, response) {
            request.urlParsed = local.url.parse(request.url);
            if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
                response.end(local.assetsDict[request.urlParsed.pathname]);
                return;
            }
            response.statusCode = 404;
            response.end();
        }).listen(process.env.PORT);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-sinopia/lib.npmtest_sinopia.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/lib.npmtest_sinopia.js

Statements: 100% (16 / 16)      Branches: 100% (14 / 14)      Functions: 100% (3 / 3)      Lines: 100% (16 / 16)      Ignored: none     

All files » node-npmtest-sinopia/ » lib.npmtest_sinopia.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                      2   2         2   2   2 2 2         1             2       2   2   2 1   1 1 1          
/* istanbul instrument in package npmtest_sinopia */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        // init utility2_rollup
        local = local.global.utility2_rollup || local;
        // init lib
        local.local = local.npmtest_sinopia = local;
        // init exports
        if (local.modeJs === 'browser') {
            local.global.utility2_npmtest_sinopia = local;
        } else {
            module.exports = local;
            module.exports.__dirname = __dirname;
            module.exports.module = module;
        }
    }());
}());
 
 
Code coverage report for node-npmtest-sinopia/test.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/test.js

Statements: 100% (48 / 48)      Branches: 100% (35 / 35)      Functions: 100% (11 / 11)      Lines: 100% (48 / 48)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177                      2   2         2   2   2 2 2         1             2     2     1       1     1   1     2           2 2   2           1           1           2 2   2             1     1             1             1 1     1             1 1 1 1 1     1             2 2     1             2 2     1             2 2     1             1 1       1 1        
/* istanbul instrument in package npmtest_sinopia */
/*jslint
    bitwise: true,
    browser: true,
    maxerr: 8,
    maxlen: 96,
    node: true,
    nomen: true,
    regexp: true,
    stupid: true
*/
(function () {
    'use strict';
    var local;
 
 
 
    // run shared js-env code - pre-init
    (function () {
        // init local
        local = {};
        // init modeJs
        local.modeJs = (function () {
            try {
                return typeof navigator.userAgent === 'string' &&
                    typeof document.querySelector('body') === 'object' &&
                    typeof XMLHttpRequest.prototype.open === 'function' &&
                    'browser';
            } catch (errorCaughtBrowser) {
                return module.exports &&
                    typeof process.versions.node === 'string' &&
                    typeof require('http').createServer === 'function' &&
                    'node';
            }
        }());
        // init global
        local.global = local.modeJs === 'browser'
            ? window
            : global;
        switch (local.modeJs) {
        // re-init local from window.local
        case 'browser':
            local = local.global.utility2.objectSetDefault(
                local.global.utility2_rollup || local.global.local,
                local.global.utility2
            );
            break;
        // re-init local from example.js
        case 'node':
            local = (local.global.utility2_rollup || require('utility2'))
                .requireExampleJsFromReadme();
            break;
        }
        // export local
        local.global.local = local;
    }());
 
 
 
    // run shared js-env code - function
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - function
    case 'browser':
        break;
 
 
 
    // run node js-env code - function
    case 'node':
        break;
    }
 
 
 
    // run shared js-env code - post-init
    (function () {
        return;
    }());
    switch (local.modeJs) {
 
 
 
    // run browser js-env code - post-init
    case 'browser':
        // run tests
        local.nop(local.modeTest &&
            document.querySelector('#testRunButton1') &&
            document.querySelector('#testRunButton1').click());
        break;
 
 
 
    // run node js-env code - post-init
    /* istanbul ignore next */
    case 'node':
        local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApidoc's default handling-behavior-behavior
         */
            options = { modulePathList: module.paths };
            local.buildApidoc(options, onError);
        };
 
        local.testCase_buildApp_default = local.testCase_buildApp_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildApp's default handling-behavior-behavior
         */
            local.testCase_buildReadme_default(options, local.onErrorThrow);
            local.testCase_buildLib_default(options, local.onErrorThrow);
            local.testCase_buildTest_default(options, local.onErrorThrow);
            options = [];
            local.buildApp(options, onError);
        };
 
        local.testCase_buildLib_default = local.testCase_buildLib_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildLib's default handling-behavior
         */
            options = {};
            local.buildLib(options, onError);
        };
 
        local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildReadme's default handling-behavior-behavior
         */
            options = {};
            local.buildReadme(options, onError);
        };
 
        local.testCase_buildTest_default = local.testCase_buildTest_default || function (
            options,
            onError
        ) {
        /*
         * this function will test buildTest's default handling-behavior
         */
            options = {};
            local.buildTest(options, onError);
        };
 
        local.testCase_webpage_default = local.testCase_webpage_default || function (
            options,
            onError
        ) {
        /*
         * this function will test webpage's default handling-behavior
         */
            options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
            local.browserTest(options, onError);
        };
 
        // run test-server
        local.testRunServer(local);
        break;
    }
}());
 
 
Code coverage report for node-npmtest-sinopia/sinopia/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/
File Statements Branches Functions Lines
index.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/index.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 121 1                    
require('es6-shim')
module.exports = require('./lib')
 
/**package
{ "name": "sinopia",
  "version": "0.0.0",
  "dependencies": {"js-yaml": "*"},
  "scripts": {"postinstall": "js-yaml package.yaml > package.json ; npm install"}
}
**/
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/

Statements: 15.2% (271 / 1783)      Branches: 0.11% (1 / 921)      Functions: 1.18% (4 / 339)      Lines: 16.3% (271 / 1663)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/lib/
File Statements Branches Functions Lines
auth.js 10.81% (24 / 222) 0% (0 / 110) 0% (0 / 38) 11.82% (24 / 203)
config.js 17.27% (19 / 110) 0% (0 / 53) 0% (0 / 11) 19% (19 / 100)
index.js 17.46% (11 / 63) 0% (0 / 35) 0% (0 / 10) 18.33% (11 / 60)
local-data.js 32% (8 / 25) 0% (0 / 4) 0% (0 / 5) 32% (8 / 25)
local-fs.js 21.64% (37 / 171) 0% (0 / 52) 0% (0 / 52) 23.87% (37 / 155)
local-storage.js 11.86% (46 / 388) 0.52% (1 / 193) 2.67% (2 / 75) 12.64% (46 / 364)
logger.js 17.33% (13 / 75) 0% (0 / 49) 0% (0 / 10) 18.31% (13 / 71)
middleware.js 13.51% (15 / 111) 0% (0 / 63) 0% (0 / 21) 14.29% (15 / 105)
plugin-loader.js 15.38% (4 / 26) 0% (0 / 22) 0% (0 / 3) 15.38% (4 / 26)
search.js 53.85% (14 / 26) 0% (0 / 4) 25% (2 / 8) 56% (14 / 25)
status-cats.js 27.27% (3 / 11) 0% (0 / 4) 0% (0 / 3) 27.27% (3 / 11)
storage.js 11.98% (29 / 242) 0% (0 / 118) 0% (0 / 55) 13.18% (29 / 220)
streams.js 32.14% (9 / 28) 0% (0 / 6) 0% (0 / 6) 32.14% (9 / 28)
up-storage.js 11.82% (24 / 203) 0% (0 / 145) 0% (0 / 30) 12.24% (24 / 196)
utils.js 18.29% (15 / 82) 0% (0 / 63) 0% (0 / 12) 20.27% (15 / 74)
Code coverage report for node-npmtest-sinopia/sinopia/lib/auth.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/auth.js

Statements: 10.81% (24 / 222)      Branches: 0% (0 / 110)      Functions: 0% (0 / 38)      Lines: 11.82% (24 / 203)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 3821 1 1 1 1   1   1                                                                                           1                                                                 1                                     1                                           1                                       1                                       1       1                                                                                                     1       1                                                                     1       1                                                                                     1                       1                                             1             1                     1                 1                    
var Crypto       = require('crypto')
var jju          = require('jju')
var Error        = require('http-errors')
var Logger       = require('./logger')
var load_plugins = require('./plugin-loader').load_plugins
 
module.exports = Auth
 
function Auth(config) {
  var self = Object.create(Auth.prototype)
  self.config = config
  self.logger = Logger.logger.child({ sub: 'auth' })
  self.secret = config.secret
 
  var plugin_params = {
    config: config,
    logger: self.logger
  }
 
  if (config.users_file) {
    if (!config.auth || !config.auth.htpasswd) {
      // b/w compat
      config.auth = config.auth || {}
      config.auth.htpasswd = { file: config.users_file }
    }
  }
 
  self.plugins = load_plugins(config, config.auth, plugin_params, function (p) {
    return p.authenticate || p.allow_access || p.allow_publish
  })
 
  self.plugins.unshift({
    sinopia_version: '1.1.0',
 
    authenticate: function(user, password, cb) {
      if (config.users != null
       && config.users[user] != null
       && (Crypto.createHash('sha1').update(password).digest('hex')
            === config.users[user].password)
      ) {
        return cb(null, [ user ])
      }
 
      return cb()
    },
 
    adduser: function(user, password, cb) {
      if (config.users && config.users[user])
        return cb( Error[403]('this user already exists') )
 
      return cb()
    },
  })
 
  function allow_action(action) {
    return function(user, package, cb) {
      var ok = package[action].reduce(function(prev, curr) {
        if (user.groups.indexOf(curr) !== -1) return true
        return prev
      }, false)
 
      if (ok) return cb(null, true)
 
      if (user.name) {
        cb( Error[403]('user ' + user.name + ' is not allowed to ' + action + ' package ' + package.name) )
      } else {
        cb( Error[403]('unregistered users are not allowed to ' + action + ' package ' + package.name) )
      }
    }
  }
 
  self.plugins.push({
    authenticate: function(user, password, cb) {
      return cb( Error[403]('bad username/password, access denied') )
    },
 
    add_user: function(user, password, cb) {
      return cb( Error[409]('registration is disabled') )
    },
 
    allow_access: allow_action('access'),
    allow_publish: allow_action('publish'),
  })
 
  return self
}
 
Auth.prototype.authenticate = function(user, password, cb) {
  var plugins = this.plugins.slice(0)
 
  ;(function next() {
    var p = plugins.shift()
 
    if (typeof(p.authenticate) !== 'function') {
      return next()
    }
 
    p.authenticate(user, password, function(err, groups) {
      if (err) return cb(err)
      if (groups != null && groups != false)
        return cb(err, AuthenticatedUser(user, groups))
      next()
    })
  })()
}
 
Auth.prototype.add_user = function(user, password, cb) {
  var self = this
  var plugins = this.plugins.slice(0)
 
  ;(function next() {
    var p = plugins.shift()
    var n = 'adduser'
    if (typeof(p[n]) !== 'function') {
      n = 'add_user'
    }
    if (typeof(p[n]) !== 'function') {
      next()
    } else {
      p[n](user, password, function(err, ok) {
        if (err) return cb(err)
        if (ok) return self.authenticate(user, password, cb)
        next()
      })
    }
  })()
}
 
Auth.prototype.allow_access = function(package_name, user, callback) {
  var plugins = this.plugins.slice(0)
  var package = Object.assign({ name: package_name },
                              this.config.get_package_spec(package_name))
 
  ;(function next() {
    var p = plugins.shift()
 
    if (typeof(p.allow_access) !== 'function') {
      return next()
    }
 
    p.allow_access(user, package, function(err, ok) {
      if (err) return callback(err)
      if (ok) return callback(null, ok)
      next() // cb(null, false) causes next plugin to roll
    })
  })()
}
 
Auth.prototype.allow_publish = function(package_name, user, callback) {
  var plugins = this.plugins.slice(0)
  var package = Object.assign({ name: package_name },
                              this.config.get_package_spec(package_name))
 
  ;(function next() {
    var p = plugins.shift()
 
    if (typeof(p.allow_publish) !== 'function') {
      return next()
    }
 
    p.allow_publish(user, package, function(err, ok) {
      if (err) return callback(err)
      if (ok) return callback(null, ok)
      next() // cb(null, false) causes next plugin to roll
    })
  })()
}
 
Auth.prototype.basic_middleware = function() {
  var self = this
  return function(req, res, _next) {
    req.pause()
    function next(err) {
      req.resume()
      // uncomment this to reject users with bad auth headers
      //return _next.apply(null, arguments)
 
      // swallow error, user remains unauthorized
      // set remoteUserError to indicate that user was attempting authentication
      if (err) req.remote_user.error = err.message
      return _next()
    }
 
    if (req.remote_user != null && req.remote_user.name !== undefined)
      return next()
    req.remote_user = AnonymousUser()
 
    var authorization = req.headers.authorization
    if (authorization == null) return next()
 
    var parts = authorization.split(' ')
 
    if (parts.length !== 2)
      return next( Error[400]('bad authorization header') )
 
    var scheme = parts[0]
    if (scheme === 'Basic') {
      var credentials = Buffer(parts[1], 'base64').toString()
    } else if (scheme === 'Bearer') {
      var credentials = self.aes_decrypt(Buffer(parts[1], 'base64')).toString('utf8')
      if (!credentials) return next()
    } else {
      return next()
    }
 
    var index = credentials.indexOf(':')
    if (index < 0) return next()
 
    var user = credentials.slice(0, index)
    var pass = credentials.slice(index + 1)
 
    self.authenticate(user, pass, function(err, user) {
      if (!err) {
        req.remote_user = user
        next()
      } else {
        req.remote_user = AnonymousUser()
        next(err)
      }
    })
  }
}
 
Auth.prototype.bearer_middleware = function() {
  var self = this
  return function(req, res, _next) {
    req.pause()
    function next(_err) {
      req.resume()
      return _next.apply(null, arguments)
    }
 
    if (req.remote_user != null && req.remote_user.name !== undefined)
      return next()
    req.remote_user = AnonymousUser()
 
    var authorization = req.headers.authorization
    if (authorization == null) return next()
 
    var parts = authorization.split(' ')
 
    if (parts.length !== 2)
      return next( Error[400]('bad authorization header') )
 
    var scheme = parts[0]
    var token = parts[1]
 
    if (scheme !== 'Bearer')
      return next()
 
    try {
      var user = self.decode_token(token)
    } catch(err) {
      return next(err)
    }
 
    req.remote_user = AuthenticatedUser(user.u, user.g)
    req.remote_user.token = token
    next()
  }
}
 
Auth.prototype.cookie_middleware = function() {
  var self = this
  return function(req, res, _next) {
    req.pause()
    function next(_err) {
      req.resume()
      return _next()
    }
 
    if (req.remote_user != null && req.remote_user.name !== undefined)
      return next()
 
    req.remote_user = AnonymousUser()
 
    var token = req.cookies.get('token')
    if (token == null) return next()
 
    /*try {
      var user = self.decode_token(token, 60*60)
    } catch(err) {
      return next()
    }
 
    req.remote_user = AuthenticatedUser(user.u, user.g)
    req.remote_user.token = token
    next()*/
    var credentials = self.aes_decrypt(Buffer(token, 'base64')).toString('utf8')
    if (!credentials) return next()
 
    var index = credentials.indexOf(':')
    if (index < 0) return next()
 
    var user = credentials.slice(0, index)
    var pass = credentials.slice(index + 1)
 
    self.authenticate(user, pass, function(err, user) {
      if (!err) {
        req.remote_user = user
        next()
      } else {
        req.remote_user = AnonymousUser()
        next(err)
      }
    })
  }
}
 
Auth.prototype.issue_token = function(user) {
  var data = jju.stringify({
    u: user.name,
    g: user.real_groups && user.real_groups.length ? user.real_groups : undefined,
    t: ~~(Date.now()/1000),
  }, { indent: false })
 
  data = Buffer(data, 'utf8')
  var mac = Crypto.createHmac('sha256', this.secret).update(data).digest()
  return Buffer.concat([ data, mac ]).toString('base64')
}
 
Auth.prototype.decode_token = function(str, expire_time) {
  var buf = Buffer(str, 'base64')
  if (buf.length <= 32) throw Error[401]('invalid token')
 
  var data      = buf.slice(0, buf.length - 32)
  var their_mac = buf.slice(buf.length - 32)
  var good_mac  = Crypto.createHmac('sha256', this.secret).update(data).digest()
 
  their_mac = Crypto.createHash('sha512').update(their_mac).digest('hex')
  good_mac  = Crypto.createHash('sha512').update(good_mac).digest('hex')
  if (their_mac !== good_mac) throw Error[401]('bad signature')
 
  // make token expire in 24 hours
  // TODO: make configurable?
  expire_time = expire_time || 24*60*60
 
  data = jju.parse(data.toString('utf8'))
  if (Math.abs(data.t - ~~(Date.now()/1000)) > expire_time)
    throw Error[401]('token expired')
 
  return data
}
 
Auth.prototype.aes_encrypt = function(buf) {
  var c = Crypto.createCipher('aes192', this.secret)
  var b1 = c.update(buf)
  var b2 = c.final()
  return Buffer.concat([ b1, b2 ])
}
 
Auth.prototype.aes_decrypt = function(buf) {
  try {
    var c = Crypto.createDecipher('aes192', this.secret)
    var b1 = c.update(buf)
    var b2 = c.final()
  } catch(_) {
    return Buffer(0)
  }
  return Buffer.concat([ b1, b2 ])
}
 
function AnonymousUser() {
  return {
    name: undefined,
    // groups without '$' are going to be deprecated eventually
    groups: [ '$all', '$anonymous', '@all', '@anonymous', 'all', 'undefined', 'anonymous' ],
    real_groups: [],
  }
}
 
function AuthenticatedUser(name, groups) {
  var _groups = (groups || []).concat([ '$all', '$authenticated', '@all', '@authenticated', 'all' ])
  return {
    name: name,
    groups: _groups,
    real_groups: groups,
  }
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/config.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/config.js

Statements: 17.27% (19 / 110)      Branches: 0% (0 / 53)      Functions: 0% (0 / 11)      Lines: 19% (19 / 100)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 2001 1 1 1 1 1 1 1 1 1 1     1                       1                                                                                                                     1                                                                                                                                 1             1                 1   1                       1                                        
var assert    = require('assert')
var Crypto    = require('crypto')
var fs        = require('fs')
var YAML      = require('js-yaml')
var Error     = require('http-errors')
var minimatch = require('minimatch')
var Path      = require('path')
var LocalData = require('./local-data')
var Utils     = require('./utils')
var pkg_file  = '../package.yaml'
var pkg       = YAML.safeLoad(fs.readFileSync(__dirname+'/'+pkg_file, 'utf8'))
 
// [[a, [b, c]], d] -> [a, b, c, d]
function flatten(array) {
  var result = []
  for (var i=0; i<array.length; i++) {
    if (Array.isArray(array[i])) {
      result.push.apply(result, flatten(array[i]))
    } else {
      result.push(array[i])
    }
  }
  return result
}
 
function Config(config) {
  var self = Object.create(Config.prototype)
  for (var i in config) {
    if (self[i] == null) self[i] = config[i]
  }
  if (!self.user_agent) self.user_agent = 'Sinopia/'+pkg.version
 
  // some weird shell scripts are valid yaml files parsed as string
  assert.equal(typeof(config), 'object', 'CONFIG: it doesn\'t look like a valid config file')
 
  assert(self.storage, 'CONFIG: storage path not defined')
  self.localList = LocalData(
    Path.join(
      Path.resolve(Path.dirname(self.self_path), self.storage),
      '.sinopia-db.json'
    )
  )
  if (!self.secret) {
    self.secret = self.localList.data.secret
 
    if (!self.secret) {
      self.secret = Crypto.pseudoRandomBytes(32).toString('hex')
      self.localList.data.secret = self.secret
      self.localList.sync()
    }
  }
 
  var users = {all:true, anonymous:true, 'undefined':true, owner:true, none:true}
 
  var check_user_or_uplink = function(arg) {
    assert(arg !== 'all' && arg !== 'owner' && arg !== 'anonymous' && arg !== 'undefined' && arg !== 'none', 'CONFIG: reserved user/uplink name: ' + arg)
    assert(!arg.match(/\s/), 'CONFIG: invalid user name: ' + arg)
    assert(users[arg] == null, 'CONFIG: duplicate user/uplink name: ' + arg)
    users[arg] = true
  }
 
  ;[ 'users', 'uplinks', 'packages' ].forEach(function(x) {
    if (self[x] == null) self[x] = {}
    assert(Utils.is_object(self[x]), 'CONFIG: bad "'+x+'" value (object expected)')
  })
 
  for (var i in self.users) check_user_or_uplink(i)
  for (var i in self.uplinks) check_user_or_uplink(i)
 
  for (var i in self.users) {
    assert(self.users[i].password, 'CONFIG: no password for user: ' + i)
    assert(
      typeof(self.users[i].password) === 'string' &&
      self.users[i].password.match(/^[a-f0-9]{40}$/)
    , 'CONFIG: wrong password format for user: ' + i + ', sha1 expected')
  }
 
  for (var i in self.uplinks) {
    assert(self.uplinks[i].url, 'CONFIG: no url for uplink: ' + i)
    assert( typeof(self.uplinks[i].url) === 'string'
          , 'CONFIG: wrong url format for uplink: ' + i)
    self.uplinks[i].url = self.uplinks[i].url.replace(/\/$/, '')
  }
 
  function normalize_userlist() {
    var result = []
 
    for (var i=0; i<arguments.length; i++) {
      if (arguments[i] == null) continue
 
      // if it's a string, split it to array
      if (typeof(arguments[i]) === 'string') {
        result.push(arguments[i].split(/\s+/))
      } else if (Array.isArray(arguments[i])) {
        result.push(arguments[i])
      } else {
        throw Error('CONFIG: bad package acl (array or string expected): ' + JSON.stringify(arguments[i]))
      }
    }
    return flatten(result)
  }
 
  // add a default rule for all packages to make writing plugins easier
  if (self.packages['**'] == null) {
    self.packages['**'] = {}
  }
 
  for (var i in self.packages) {
    assert(
      typeof(self.packages[i]) === 'object' &&
      !Array.isArray(self.packages[i])
    , 'CONFIG: bad "'+i+'" package description (object expected)')
 
    self.packages[i].access = normalize_userlist(
      self.packages[i].allow_access,
      self.packages[i].access
    );
    delete self.packages[i].allow_access
 
    self.packages[i].publish = normalize_userlist(
      self.packages[i].allow_publish,
      self.packages[i].publish
    );
    delete self.packages[i].allow_publish
 
    self.packages[i].proxy = normalize_userlist(
      self.packages[i].proxy_access,
      self.packages[i].proxy
    );
    delete self.packages[i].proxy_access
  }
 
  // loading these from ENV if aren't in config
  ;[ 'http_proxy', 'https_proxy', 'no_proxy' ].forEach((function(v) {
    if (!(v in self)) {
      self[v] = process.env[v] || process.env[v.toUpperCase()]
    }
  }).bind(self))
 
  // unique identifier of self server (or a cluster), used to avoid loops
  if (!self.server_id) {
    self.server_id = Crypto.pseudoRandomBytes(6).toString('hex')
  }
 
  if (self.ignore_latest_tag == null) self.ignore_latest_tag = false
 
  return self
}
 
Config.prototype.can_proxy_to = function(package, uplink) {
  return (this.get_package_spec(package).proxy || []).reduce(function(prev, curr) {
    if (uplink === curr) return true
    return prev
  }, false)
}
 
Config.prototype.get_package_spec = function(package) {
  for (var i in this.packages) {
    if (minimatch.makeRe(i).exec(package)) {
      return this.packages[i]
    }
  }
  return {}
}
 
module.exports = Config
 
var parse_interval_table = {
  '': 1000,
  ms: 1,
  s: 1000,
  m: 60*1000,
  h: 60*60*1000,
  d: 86400000,
  w: 7*86400000,
  M: 30*86400000,
  y: 365*86400000,
}
 
module.exports.parse_interval = function(interval) {
  if (typeof(interval) === 'number') return interval * 1000
 
  var result = 0
  var last_suffix = Infinity
  interval.split(/\s+/).forEach(function(x) {
    if (!x) return
    var m = x.match(/^((0|[1-9][0-9]*)(\.[0-9]+)?)(ms|s|m|h|d|w|M|y|)$/)
    if (!m
    ||  parse_interval_table[m[4]] >= last_suffix
    ||  (m[4] === '' && last_suffix !== Infinity)) {
      throw Error('invalid interval: ' + interval)
    }
    last_suffix = parse_interval_table[m[4]]
    result += Number(m[1]) * parse_interval_table[m[4]]
  })
  return result
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/index.js

Statements: 17.46% (11 / 63)      Branches: 0% (0 / 35)      Functions: 0% (0 / 10)      Lines: 18.33% (11 / 60)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 1071 1 1 1 1 1 1 1 1   1                       1                                                                                                                                                                        
var express       = require('express')
var Error         = require('http-errors')
var compression   = require('compression')
var Auth          = require('./auth')
var Logger        = require('./logger')
var Config        = require('./config')
var Middleware    = require('./middleware')
var Cats          = require('./status-cats')
var Storage       = require('./storage')
 
module.exports = function(config_hash) {
  Logger.setup(config_hash.logs)
 
  var config  = Config(config_hash)
  var storage = Storage(config)
  var auth    = Auth(config)
  var app     = express()
 
  // run in production mode by default, just in case
  // it shouldn't make any difference anyway
  app.set('env', process.env.NODE_ENV || 'production')
 
  function error_reporting_middleware(req, res, next) {
    res.report_error = res.report_error || function(err) {
      if (err.status && err.status >= 400 && err.status < 600) {
        if (!res.headersSent) {
          res.status(err.status)
          next({ error: err.message || 'unknown error' })
        }
      } else {
        Logger.logger.error( { err: err }
                           , 'unexpected error: @{!err.message}\n@{err.stack}')
        if (!res.status || !res.send) {
          Logger.logger.error('this is an error in express.js, please report this')
          res.destroy()
        } else if (!res.headersSent) {
          res.status(500)
          next({ error: 'internal server error' })
        } else {
          // socket should be already closed
        }
      }
    }
    next()
  }
 
  app.use(Middleware.log)
  app.use(error_reporting_middleware)
  app.use(function(req, res, next) {
    res.setHeader('X-Powered-By', config.user_agent)
    next()
  })
  app.use(Cats.middleware)
  app.use(compression())
 
  app.get('/favicon.ico', function(req, res, next) {
    req.url = '/-/static/favicon.png'
    next()
  })
 
  // hook for tests only
  if (config._debug) {
    app.get('/-/_debug', function(req, res, next) {
      var do_gc = typeof(global.gc) !== 'undefined'
      if (do_gc) global.gc()
      next({
        pid  : process.pid,
        main : process.mainModule.filename,
        conf : config.self_path,
        mem  : process.memoryUsage(),
        gc   : do_gc,
      })
    })
  }
 
  app.use(require('./index-api')(config, auth, storage))
 
  if (config.web && config.web.enable === false) {
    app.get('/', function(req, res, next) {
      next( Error[404]('web interface is disabled in the config file') )
    })
  } else {
    app.use(require('./index-web')(config, auth, storage))
  }
 
  app.get('/*', function(req, res, next) {
    next( Error[404]('file not found') )
  })
 
  app.use(function(err, req, res, next) {
    if (Object.prototype.toString.call(err) !== '[object Error]') return next(err)
    if (err.code === 'ECONNABORT' && res.statusCode === 304) return next()
    if (typeof(res.report_error) !== 'function') {
      // in case of very early error this middleware may not be loaded before error is generated
      // fixing that
      error_reporting_middleware(req, res, function(){})
    }
    res.report_error(err)
  })
 
  app.use(Middleware.final)
 
  return app
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/local-data.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/local-data.js

Statements: 32% (8 / 25)      Branches: 0% (0 / 4)      Functions: 0% (0 / 5)      Lines: 32% (8 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 461 1   1   1                     1             1                 1       1                  
var fs   = require('fs')
var Path = require('path')
 
module.exports = LocalData
 
function LocalData(path) {
  var self = Object.create(LocalData.prototype)
  self.path = path
  try {
    self.data = JSON.parse(fs.readFileSync(self.path, 'utf8'))
  } catch(_) {
    self.data = { list: [] }
  }
  return self
}
 
LocalData.prototype.add = function(name) {
  if (this.data.list.indexOf(name) === -1) {
    this.data.list.push(name)
    this.sync()
  }
}
 
LocalData.prototype.remove = function(name) {
  var i = this.data.list.indexOf(name)
  if (i !== -1) {
    this.data.list.splice(i, 1)
  }
 
  this.sync()
}
 
LocalData.prototype.get = function() {
  return this.data.list
}
 
LocalData.prototype.sync = function() {
  // Uses sync to prevent ugly race condition
  try {
    require('mkdirp').sync(Path.dirname(this.path))
  } catch(err) {}
  fs.writeFileSync(this.path, JSON.stringify(this.data))
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/local-fs.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/local-fs.js

Statements: 21.64% (37 / 171)      Branches: 0% (0 / 52)      Functions: 0% (0 / 52)      Lines: 23.87% (37 / 155)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 2791 1 1 1 1   1           1 1   1             1       1 1                                   1                                         1                                 1                                                                             1                                         1             1             1         1                                                   1   1                                     1                   1   1                           1   1                           1   1       1   1       1   1       1   1   1   1      
var fs        = require('fs')
var Error     = require('http-errors')
var mkdirp    = require('mkdirp')
var Path      = require('path')
var MyStreams = require('./streams')
 
function FSError(code) {
  var err = Error(code)
  err.code = code
  return err
}
 
try {
  var fsExt = require('fs-ext')
} catch (e) {
  fsExt = {
    flock: function() {
      arguments[arguments.length-1]()
    }
  }
}
 
function tempFile(str) {
  return str + '.tmp' + String(Math.random()).substr(2)
}
 
function renameTmp(src, dst, _cb) {
  function cb(err) {
    if (err) fs.unlink(src)
    _cb(err)
  }
 
  if (process.platform !== 'win32') {
    return fs.rename(src, dst, cb)
  }
 
  // windows can't remove opened file,
  // but it seem to be able to rename it
  var tmp = tempFile(dst)
  fs.rename(dst, tmp, function(err) {
    fs.rename(src, dst, cb)
    if (!err) fs.unlink(tmp)
  })
}
 
function write(dest, data, cb) {
  var safe_write = function(cb) {
    var tmpname = tempFile(dest)
    fs.writeFile(tmpname, data, function(err) {
      if (err) return cb(err)
      renameTmp(tmpname, dest, cb)
    })
  }
 
  safe_write(function(err) {
    if (err && err.code === 'ENOENT') {
      mkdirp(Path.dirname(dest), function(err) {
        if (err) return cb(err)
        safe_write(cb)
      })
    } else {
      cb(err)
    }
  })
}
 
function write_stream(name) {
  var stream = MyStreams.UploadTarballStream()
 
  var _ended = 0
  stream.on('end', function() {
    _ended = 1
  })
 
  fs.exists(name, function(exists) {
    if (exists) return stream.emit('error', FSError('EEXISTS'))
 
    var tmpname = name + '.tmp-'+String(Math.random()).replace(/^0\./, '')
    var file = fs.createWriteStream(tmpname)
    var opened = false
    stream.pipe(file)
 
    stream.done = function() {
      function onend() {
        file.on('close', function() {
          renameTmp(tmpname, name, function(err) {
            if (err) {
              stream.emit('error', err)
            } else {
              stream.emit('success')
            }
          })
        })
        file.destroySoon()
      }
      if (_ended) {
        onend()
      } else {
        stream.on('end', onend)
      }
    }
    stream.abort = function() {
      if (opened) {
        opened = false
        file.on('close', function() {
          fs.unlink(tmpname, function(){})
        })
      }
      file.destroySoon()
    }
    file.on('open', function() {
      opened = true
      // re-emitting open because it's handled in storage.js
      stream.emit('open')
    })
    file.on('error', function(err) {
      stream.emit('error', err)
    })
  })
  return stream
}
 
function read_stream(name, stream, callback) {
  var rstream = fs.createReadStream(name)
  rstream.on('error', function(err) {
    stream.emit('error', err)
  })
  rstream.on('open', function(fd) {
    fs.fstat(fd, function(err, stats) {
      if (err) return stream.emit('error', err)
      stream.emit('content-length', stats.size)
      stream.emit('open')
      rstream.pipe(stream)
    })
  })
 
  var stream = MyStreams.ReadTarballStream()
  stream.abort = function() {
    rstream.close()
  }
  return stream
}
 
function create(name, contents, callback) {
  fs.exists(name, function(exists) {
    if (exists) return callback( FSError('EEXISTS') )
    write(name, contents, callback)
  })
}
 
function update(name, contents, callback) {
  fs.exists(name, function(exists) {
    if (!exists) return callback( FSError('ENOENT') )
    write(name, contents, callback)
  })
}
 
function read(name, callback) {
  fs.readFile(name, callback)
}
 
// open and flock with exponential backoff
function open_flock(name, opmod, flmod, tries, backoff, cb) {
  fs.open(name, opmod, function(err, fd) {
    if (err) return cb(err, fd)
 
    fsExt.flock(fd, flmod, function(err) {
      if (err) {
        if (!tries) {
          fs.close(fd, function() {
            cb(err)
          })
        } else {
          fs.close(fd, function() {
            setTimeout(function() {
              open_flock(name, opmod, flmod, tries-1, backoff*2, cb)
            }, backoff)
          })
        }
      } else {
        cb(null, fd)
      }
    })
  })
}
 
// this function neither unlocks file nor closes it
// it'll have to be done manually later
function lock_and_read(name, _callback) {
  open_flock(name, 'r', 'exnb', 4, 10, function(err, fd) {
    function callback(err) {
      if (err && fd) {
        fs.close(fd, function(err2) {
          _callback(err)
        })
      } else {
        _callback.apply(null, arguments)
      }
    }
 
    if (err) return callback(err, fd)
 
    fs.fstat(fd, function(err, st) {
      if (err) return callback(err, fd)
 
      var buffer = Buffer(st.size)
      if (st.size === 0) return onRead(null, 0, buffer)
      fs.read(fd, buffer, 0, st.size, null, onRead)
 
      function onRead(err, bytesRead, buffer) {
        if (err) return callback(err, fd)
        if (bytesRead != st.size) return callback(Error('st.size != bytesRead'), fd)
 
        callback(null, fd, buffer)
      }
    })
  })
}
 
module.exports.read = read
 
module.exports.read_json = function(name, cb) {
  read(name, function(err, res) {
    if (err) return cb(err)
 
    var args = []
    try {
      args = [ null, JSON.parse(res.toString('utf8')) ]
    } catch(err) {
      args = [ err ]
    }
    cb.apply(null, args)
  })
}
 
module.exports.lock_and_read = lock_and_read
 
module.exports.lock_and_read_json = function(name, cb) {
  lock_and_read(name, function(err, fd, res) {
    if (err) return cb(err, fd)
 
    var args = []
    try {
      args = [ null, fd, JSON.parse(res.toString('utf8')) ]
    } catch(err) {
      args = [ err, fd ]
    }
    cb.apply(null, args)
  })
}
 
module.exports.create = create
 
module.exports.create_json = function(name, value, cb) {
  create(name, JSON.stringify(value, null, '\t'), cb)
}
 
module.exports.update = update
 
module.exports.update_json = function(name, value, cb) {
  update(name, JSON.stringify(value, null, '\t'), cb)
}
 
module.exports.write = write
 
module.exports.write_json = function(name, value, cb) {
  write(name, JSON.stringify(value, null, '\t'), cb)
}
 
module.exports.write_stream = write_stream
 
module.exports.read_stream = read_stream
 
module.exports.unlink = fs.unlink
 
module.exports.rmdir = fs.rmdir
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/local-storage.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/local-storage.js

Statements: 11.86% (46 / 388)      Branches: 0.52% (1 / 193)      Functions: 2.67% (2 / 75)      Lines: 12.64% (46 / 364)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 7021 1 1 1 1 1 1 1 1 1 1 1 1 1           1               1                           1           1                                 1                                             1                                           1                                                 1                                                                                                                                                                             1                                                                   1                                       1                                             1                                                         1                                   1                                                                                                                                                                         1                                                                       1                                         1                                                                                                                                   1         1                                                             1                                                                                                 1             1                       1                               1   1           1 14 14       1 14             1     1      
var assert     = require('assert')
var async      = require('async')
var Crypto     = require('crypto')
var fs         = require('fs')
var Error      = require('http-errors')
var Path       = require('path')
var Stream     = require('readable-stream')
var URL        = require('url')
var fs_storage = require('./local-fs')
var Logger     = require('./logger')
var Search     = require('./search')
var MyStreams  = require('./streams')
var Utils      = require('./utils')
var info_file  = 'package.json'
 
//
// Implements Storage interface
// (same for storage.js, local-storage.js, up-storage.js)
//
function Storage(config) {
  var self = Object.create(Storage.prototype)
  self.config = config
  self.logger = Logger.logger.child({ sub: 'fs' })
  return self
}
 
// returns the minimal package file
function get_boilerplate(name) {
  return {
    // standard things
    name: name,
    versions: {},
    'dist-tags': {},
 
    // our own object
    '_distfiles': {},
    '_attachments': {},
    '_uplinks': {},
  }
}
 
Storage.prototype._internal_error = function(err, file, message) {
  this.logger.error( { err: err, file: file }
                   , message + ' @{file}: @{!err.message}' )
  return Error[500]()
}
 
Storage.prototype.add_package = function(name, info, callback) {
  var storage = this.storage(name)
  if (!storage) return callback( Error[404]('this package cannot be added') )
 
  storage.create_json(info_file, get_boilerplate(name), function(err) {
    if (err && err.code === 'EEXISTS') {
      return callback( Error[409]('this package is already present') )
    }
 
    var latest = info['dist-tags'].latest
    if (latest && info.versions[latest]) {
      Search.add(info.versions[latest])
    }
    callback()
  })
}
 
Storage.prototype.remove_package = function(name, callback) {
  var self = this
  self.logger.info( { name: name }
                  , 'unpublishing @{name} (all)')
 
  var storage = self.storage(name)
  if (!storage) return callback( Error[404]('no such package available') )
 
  storage.read_json(info_file, function(err, data) {
    if (err) {
      if (err.code === 'ENOENT') {
        return callback( Error[404]('no such package available') )
      } else {
        return callback(err)
      }
    }
    self._normalize_package(data)
 
    storage.unlink(info_file, function(err) {
      if (err) return callback(err)
 
      var files = Object.keys(data._attachments)
 
      function unlinkNext(cb) {
        if (files.length === 0) return cb()
 
        var file = files.shift()
        storage.unlink(file, function() {
          unlinkNext(cb)
        })
      }
 
      unlinkNext(function() {
        // try to unlink the directory, but ignore errors because it can fail
        storage.rmdir('.', function(err) {
          callback(err)
        })
      })
    })
  })
 
  Search.remove(name)
  this.config.localList.remove(name)
}
 
Storage.prototype._read_create_package = function(name, callback) {
  var self = this
  var storage = self.storage(name)
  if (!storage) {
    var data = get_boilerplate(name)
    self._normalize_package(data)
    return callback(null, data)
  }
  storage.read_json(info_file, function(err, data) {
    // TODO: race condition
    if (err) {
      if (err.code === 'ENOENT') {
        // if package doesn't exist, we create it here
        data = get_boilerplate(name)
      } else {
        return callback(self._internal_error(err, info_file, 'error reading'))
      }
    }
    self._normalize_package(data)
    callback(null, data)
  })
}
 
// synchronize remote package info with the local one
// TODO: readfile called twice
Storage.prototype.update_versions = function(name, newdata, callback) {
  var self = this
  self._read_create_package(name, function(err, data) {
    if (err) return callback(err)
 
    var change = false
    for (var ver in newdata.versions) {
      if (data.versions[ver] == null) {
        var verdata = newdata.versions[ver]
 
        // we don't keep readmes for package versions,
        // only one readme per package
        delete verdata.readme
 
        change = true
        data.versions[ver] = verdata
 
        if (verdata.dist && verdata.dist.tarball) {
          var filename = URL.parse(verdata.dist.tarball).pathname.replace(/^.*\//, '')
          // we do NOT overwrite any existing records
          if (data._distfiles[filename] == null) {
            var hash = data._distfiles[filename] = {
              url: verdata.dist.tarball,
              sha: verdata.dist.shasum,
            }
 
            if (verdata._sinopia_uplink) {
              // if we got this information from a known registry,
              // use the same protocol for the tarball
              //
              // see https://github.com/rlidwka/sinopia/issues/166
              var tarball_url = URL.parse(hash.url)
              var uplink_url  = URL.parse(self.config.uplinks[verdata._sinopia_uplink].url)
              if (uplink_url.host === tarball_url.host) {
                tarball_url.protocol = uplink_url.protocol
                hash.registry = verdata._sinopia_uplink
                hash.url = URL.format(tarball_url)
              }
            }
          }
        }
      }
    }
    for (var tag in newdata['dist-tags']) {
      if (!Array.isArray(data['dist-tags'][tag]) || data['dist-tags'][tag].length != newdata['dist-tags'][tag].length) {
        // backward compat
        var need_change = true
      } else {
        for (var i=0; i<data['dist-tags'][tag].length; i++) {
          if (data['dist-tags'][tag][i] != newdata['dist-tags'][tag][i]) {
            var need_change = true
            break
          }
        }
      }
 
      if (need_change) {
        change = true
        data['dist-tags'][tag] = newdata['dist-tags'][tag]
      }
    }
    for (var up in newdata._uplinks) {
      var need_change = !Utils.is_object(data._uplinks[up])
                     || newdata._uplinks[up].etag !== data._uplinks[up].etag
                     || newdata._uplinks[up].fetched !== data._uplinks[up].fetched
 
      if (need_change) {
        change = true
        data._uplinks[up] = newdata._uplinks[up]
      }
    }
    if (newdata.readme !== data.readme) {
      data.readme = newdata.readme
      change = true
    }
 
    if (change) {
      self.logger.debug('updating package info')
      self._write_package(name, data, function(err) {
        callback(err, data)
      })
    } else {
      callback(null, data)
    }
  })
}
 
Storage.prototype.add_version = function(name, version, metadata, tag, callback) {
  var self = this
  self.update_package(name, function updater(data, cb) {
    // keep only one readme per package
    data.readme = metadata.readme
    delete metadata.readme
 
    if (data.versions[version] != null) {
      return cb( Error[409]('this version already present') )
    }
 
    // if uploaded tarball has a different shasum, it's very likely that we have some kind of error
    if (Utils.is_object(metadata.dist) && typeof(metadata.dist.tarball) === 'string') {
      var tarball = metadata.dist.tarball.replace(/.*\//, '')
      if (Utils.is_object(data._attachments[tarball])) {
        if (data._attachments[tarball].shasum != null && metadata.dist.shasum != null) {
          if (data._attachments[tarball].shasum != metadata.dist.shasum) {
            return cb( Error[400]('shasum error, '
                                + data._attachments[tarball].shasum
                                + ' != ' + metadata.dist.shasum) )
          }
        }
 
        data._attachments[tarball].version = version
      }
    }
 
    data.versions[version] = metadata
    Utils.tag_version(data, version, tag, self.config)
    self.config.localList.add(name)
    cb()
  }, callback)
}
 
Storage.prototype.merge_tags = function(name, tags, callback) {
  var self = this
 
  self.update_package(name, function updater(data, cb) {
    for (var t in tags) {
      if (tags[t] === null) {
        delete data['dist-tags'][t]
        continue
      }
 
      if (data.versions[tags[t]] == null) {
        return cb( Error[404]("this version doesn't exist") )
      }
 
      Utils.tag_version(data, tags[t], t, self.config)
    }
    cb()
  }, callback)
}
 
Storage.prototype.replace_tags = function(name, tags, callback) {
  var self = this
 
  self.update_package(name, function updater(data, cb) {
    data['dist-tags'] = {}
 
    for (var t in tags) {
      if (tags[t] === null) {
        delete data['dist-tags'][t]
        continue
      }
 
      if (data.versions[tags[t]] == null) {
        return cb( Error[404]("this version doesn't exist") )
      }
 
      Utils.tag_version(data, tags[t], t, self.config)
    }
    cb()
  }, callback)
}
 
// currently supports unpublishing only
Storage.prototype.change_package = function(name, metadata, revision, callback) {
  var self = this
 
  if (!Utils.is_object(metadata.versions) || !Utils.is_object(metadata['dist-tags'])) {
    return callback( Error[422]('bad data') )
  }
 
  self.update_package(name, function updater(data, cb) {
    for (var ver in data.versions) {
      if (metadata.versions[ver] == null) {
        self.logger.info( { name: name, version: ver }
                        , 'unpublishing @{name}@@{version}')
        delete data.versions[ver]
 
        for (var file in data._attachments) {
          if (data._attachments[file].version === ver) {
            delete data._attachments[file].version
          }
        }
      }
    }
    data['dist-tags'] = metadata['dist-tags']
    cb()
  }, function(err) {
    if (err) return callback(err)
    callback()
  })
}
 
Storage.prototype.remove_tarball = function(name, filename, revision, callback) {
  assert(Utils.validate_name(filename))
  var self = this
 
  self.update_package(name, function updater(data, cb) {
    if (data._attachments[filename]) {
      delete data._attachments[filename]
      cb()
    } else {
      cb(Error[404]('no such file available'))
    }
  }, function(err) {
    if (err) return callback(err)
    var storage = self.storage(name)
    if (storage) storage.unlink(filename, callback)
  })
}
 
Storage.prototype.add_tarball = function(name, filename) {
  assert(Utils.validate_name(filename))
 
  var stream = MyStreams.UploadTarballStream()
  var _transform = stream._transform
  var length = 0
  var shasum = Crypto.createHash('sha1')
 
  stream.abort = stream.done = function(){}
 
  stream._transform = function(data) {
    shasum.update(data)
    length += data.length
    _transform.apply(stream, arguments)
  }
 
  var self = this
  if (name === info_file || name === '__proto__') {
    process.nextTick(function() {
      stream.emit('error', Error[403]("can't use this filename"))
    })
    return stream
  }
 
  var storage = self.storage(name)
  if (!storage) {
    process.nextTick(function() {
      stream.emit('error', Error[404]("can't upload this package"))
    })
    return stream
  }
 
  var wstream = storage.write_stream(filename)
 
  wstream.on('error', function(err) {
    if (err.code === 'EEXISTS') {
      stream.emit('error', Error[409]('this tarball is already present'))
    } else if (err.code === 'ENOENT') {
      // check if package exists to throw an appropriate message
      self.get_package(name, function(_err, res) {
        if (_err) {
          stream.emit('error', _err)
        } else {
          stream.emit('error', err)
        }
      })
    } else {
      stream.emit('error', err)
    }
  })
 
  wstream.on('open', function() {
    // re-emitting open because it's handled in storage.js
    stream.emit('open')
  })
  wstream.on('success', function() {
    self.update_package(name, function updater(data, cb) {
      data._attachments[filename] = {
        shasum: shasum.digest('hex'),
      }
      cb()
    }, function(err) {
      if (err) {
        stream.emit('error', err)
      } else {
        stream.emit('success')
      }
    })
  })
  stream.abort = function() {
    wstream.abort()
  }
  stream.done = function() {
    if (!length) {
      stream.emit('error', Error[422]('refusing to accept zero-length file'))
      wstream.abort()
    } else {
      wstream.done()
    }
  }
  stream.pipe(wstream)
 
  return stream
}
 
Storage.prototype.get_tarball = function(name, filename, callback) {
  assert(Utils.validate_name(filename))
  var self = this
 
  var stream = MyStreams.ReadTarballStream()
  stream.abort = function() {
    if (rstream) rstream.abort()
  }
 
  var storage = self.storage(name)
  if (!storage) {
    process.nextTick(function() {
      stream.emit('error', Error[404]('no such file available'))
    })
    return stream
  }
 
  var rstream = storage.read_stream(filename)
  rstream.on('error', function(err) {
    if (err && err.code === 'ENOENT') {
      stream.emit('error', Error(404, 'no such file available'))
    } else {
      stream.emit('error', err)
    }
  })
  rstream.on('content-length', function(v) {
    stream.emit('content-length', v)
  })
  rstream.on('open', function() {
    // re-emitting open because it's handled in storage.js
    stream.emit('open')
    rstream.pipe(stream)
  })
  return stream
}
 
Storage.prototype.get_package = function(name, options, callback) {
  if (typeof(options) === 'function') callback = options, options = {}
 
  var self = this
  var storage = self.storage(name)
  if (!storage) return callback( Error[404]('no such package available') )
 
  storage.read_json(info_file, function(err, result) {
    if (err) {
      if (err.code === 'ENOENT') {
        return callback( Error[404]('no such package available') )
      } else {
        return callback(self._internal_error(err, info_file, 'error reading'))
      }
    }
    self._normalize_package(result)
    callback(err, result)
  })
}
 
// walks through each package and calls `on_package` on them
Storage.prototype._each_package = function (on_package, on_end) {
  var self = this
  var storages = {}
 
  storages[self.config.storage] = true
 
  if (self.config.packages) {
    Object.keys(self.packages || {}).map(function (pkg) {
      if (self.config.packages[pkg].storage) {
        storages[self.config.packages[pkg].storage] = true
      }
    })
  }
 
  var base = Path.dirname(self.config.self_path);
 
  async.eachSeries(Object.keys(storages), function (storage, cb) {
    fs.readdir(Path.resolve(base, storage), function (err, files) {
      if (err) return cb(err)
 
      async.eachSeries(files, function (file, cb) {
        if (file.match(/^@/)) {
          // scoped
          fs.readdir(Path.resolve(base, storage, file), function (err, files) {
            if (err) return cb(err)
 
            async.eachSeries(files, function (file2, cb) {
              if (Utils.validate_name(file2)) {
                on_package({
                  name: file + '/' + file2,
                  path: Path.resolve(base, storage, file, file2),
                }, cb)
              } else {
                cb()
              }
            }, cb)
          })
        } else if (Utils.validate_name(file)) {
          on_package({
            name: file,
            path: Path.resolve(base, storage, file)
          }, cb)
        } else {
          cb()
        }
      }, cb)
    })
  }, on_end)
}
 
//
// This function allows to update the package thread-safely
//
// Arguments:
// - name - package name
// - updateFn - function(package, cb) - update function
// - callback - callback that gets invoked after it's all updated
//
// Algorithm:
// 1. lock package.json for writing
// 2. read package.json
// 3. updateFn(pkg, cb), and wait for cb
// 4. write package.json.tmp
// 5. move package.json.tmp package.json
// 6. callback(err?)
//
Storage.prototype.update_package = function(name, updateFn, _callback) {
  var self = this
  var storage = self.storage(name)
  if (!storage) return _callback( Error[404]('no such package available') )
  storage.lock_and_read_json(info_file, function(err, fd, json) {
    function callback() {
      var _args = arguments
      if (fd) {
        fs.close(fd, function(err) {
          if (err) return _callback(err)
          _callback.apply(null, _args)
        })
      } else {
        _callback.apply(null, _args)
      }
    }
 
    if (err) {
      if (err.code === 'EAGAIN') {
        return callback( Error[503]('resource temporarily unavailable') )
      } else if (err.code === 'ENOENT') {
        return callback( Error[404]('no such package available') )
      } else {
        return callback(err)
      }
    }
 
    self._normalize_package(json)
    updateFn(json, function(err) {
      if (err) return callback(err)
 
      self._write_package(name, json, callback)
    })
  })
}
 
Storage.prototype.search = function(startkey, options) {
  var self = this
 
  var stream = new Stream.PassThrough({ objectMode: true })
 
  self._each_package(function on_package(item, cb) {
    fs.stat(item.path, function(err, stats) {
      if (err) return cb(err)
 
      if (stats.mtime > startkey) {
        self.get_package(item.name, options, function(err, data) {
          if (err) return cb(err)
 
          var versions = Utils.semver_sort(Object.keys(data.versions))
          var latest = versions[versions.length - 1]
 
          if (data.versions[latest]) {
            stream.push({
              name           : data.versions[latest].name,
              description    : data.versions[latest].description,
              'dist-tags'    : { latest: latest },
              maintainers    : data.versions[latest].maintainers ||
                                 [ data.versions[latest]._npmUser ].filter(Boolean),
              author         : data.versions[latest].author,
              repository     : data.versions[latest].repository,
              readmeFilename : data.versions[latest].readmeFilename || '',
              homepage       : data.versions[latest].homepage,
              keywords       : data.versions[latest].keywords,
              bugs           : data.versions[latest].bugs,
              license        : data.versions[latest].license,
              time           : { modified: item.time ? new Date(item.time).toISOString() : undefined },
              versions       : {},
            })
          }
 
          cb()
        })
      } else {
        cb()
      }
    })
  }, function on_end(err) {
    if (err) return stream.emit('error', err)
    stream.end()
  })
 
  return stream
}
 
Storage.prototype._normalize_package = function(pkg) {
  ;['versions', 'dist-tags', '_distfiles', '_attachments', '_uplinks'].forEach(function(key) {
    if (!Utils.is_object(pkg[key])) pkg[key] = {}
  })
  if (typeof(pkg._rev) !== 'string') pkg._rev = '0-0000000000000000'
}
 
Storage.prototype._write_package = function(name, json, callback) {
 
  // calculate revision a la couchdb
  if (typeof(json._rev) !== 'string') json._rev = '0-0000000000000000'
  var rev = json._rev.split('-')
  json._rev = ((+rev[0] || 0) + 1) + '-' + Crypto.pseudoRandomBytes(8).toString('hex')
 
  var storage = this.storage(name)
  if (!storage) return callback()
  storage.write_json(info_file, json, callback)
}
 
Storage.prototype.storage = function(package) {
  var path = this.config.get_package_spec(package).storage
  if (path == null) path = this.config.storage
  if (path == null || path === false) {
    this.logger.debug( { name: package }
                     , 'this package has no storage defined: @{name}' )
    return null
  }
  return Path_Wrapper(
    Path.join(
      Path.resolve(Path.dirname(this.config.self_path), path),
      package
    )
  )
}
 
var Path_Wrapper = (function() {
  // a wrapper adding paths to fs_storage methods
  function Wrapper(path) {
    var self = Object.create(Wrapper.prototype)
    self.path = path
    return self
  }
 
  for (var i in fs_storage) {
    Eif (fs_storage.hasOwnProperty(i)) {
      Wrapper.prototype[i] = wrapper(i)
    }
  }
 
  function wrapper(method) {
    return function(/*...*/) {
      var args = Array.prototype.slice.apply(arguments)
      args[0] = Path.join(this.path, args[0] || '')
      return fs_storage[method].apply(null, args)
    }
  }
 
  return Wrapper
})()
 
module.exports = Storage
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/logger.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/logger.js

Statements: 17.33% (13 / 75)      Branches: 0% (0 / 49)      Functions: 0% (0 / 10)      Lines: 18.31% (13 / 71)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 1551 1 1 1   1                       1                                                                                                                               1                   1 1 7     1         1                       1                                                                                  
var Logger = require('bunyan')
var Error  = require('http-errors')
var Stream = require('stream')
var Utils  = require('./utils')
 
function getlvl(x) {
  switch(true) {
    case x < 15  : return 'trace'
    case x < 25  : return 'debug'
    case x < 35  : return 'info'
    case x == 35 : return 'http'
    case x < 45  : return 'warn'
    case x < 55  : return 'error'
    default      : return 'fatal'
  }
}
 
module.exports.setup = function(logs) {
  var streams = []
  if (logs == null) logs = [{ type: 'stdout', format: 'pretty', level: 'http' }]
 
  logs.forEach(function(target) {
    var stream = new Stream()
    stream.writable = true
 
    if (target.type === 'stdout' || target.type === 'stderr') {
      // destination stream
      var dest = target.type === 'stdout' ? process.stdout : process.stderr
 
      if (target.format === 'pretty') {
        // making fake stream for prettypritting
        stream.write = function(obj) {
          dest.write(print(obj.level, obj.msg, obj, dest.isTTY) + '\n')
        }
      } else {
        stream.write = function(obj) {
          dest.write(JSON.stringify(obj, Logger.safeCycles()) + '\n')
        }
      }
    } else if (target.type === 'file') {
      var dest = require('fs').createWriteStream(target.path, {flags: 'a', encoding: 'utf8'})
      dest.on('error', function (err) {
        Logger.emit('error', err)
      })
      stream.write = function(obj) {
        if (target.format === 'pretty') {
          dest.write(print(obj.level, obj.msg, obj, false) + '\n')
        } else {
          dest.write(JSON.stringify(obj, Logger.safeCycles()) + '\n')
        }
      }
    } else {
      throw Error('wrong target type for a log')
    }
 
    if (target.level === 'http') target.level = 35
    streams.push({
      type: 'raw',
      level: target.level || 35,
      stream: stream,
    })
  })
 
  var logger = new Logger({
    name: 'sinopia',
    streams: streams,
    serializers: {
      err: Logger.stdSerializers.err,
      req: Logger.stdSerializers.req,
      res: Logger.stdSerializers.res,
    },
  })
 
  module.exports.logger = logger
}
 
// adopted from socket.io
// this part was converted to coffee-script and back again over the years,
// so it might look weird
 
// level to color
var levels = {
  fatal : 31,
  error : 31,
  warn  : 33,
  http  : 35,
  info  : 36,
  debug : 90,
  trace : 90,
}
 
var max = 0
for (var l in levels) {
  max = Math.max(max, l.length)
}
 
function pad(str) {
  if (str.length < max) return str + ' '.repeat(max - str.length)
  return str
}
 
var subsystems = [{
  in      : '\033[32m<--\033[39m',
  out     : '\033[33m-->\033[39m',
  fs      : '\033[90m-=-\033[39m',
  default : '\033[34m---\033[39m',
}, {
  in      : '<--',
  out     : '-->',
  fs      : '-=-',
  default : '---',
}]
 
function print(type, msg, obj, colors) {
  if (typeof type === 'number') type = getlvl(type)
  var finalmsg = msg.replace(/@{(!?[$A-Za-z_][$0-9A-Za-z\._]*)}/g, function(_, name) {
    var str = obj, is_error
    if (name[0] === '!') {
      name = name.substr(1)
      is_error = true
    }
 
    var _ref = name.split('.')
    for (var _i = 0; _i < _ref.length; _i++) {
      var id = _ref[_i]
      if (Utils.is_object(str) || Array.isArray(str)) {
        str = str[id]
      } else {
        str = undefined
      }
    }
 
    if (typeof(str) === 'string') {
      if (!colors || str.includes('\n')) {
        return str
      } else if (is_error) {
        return '\033[31m' + str + '\033[39m'
      } else {
        return '\033[32m' + str + '\033[39m'
      }
    } else {
      return require('util').inspect(str, null, null, colors)
    }
  })
 
  var sub = subsystems[colors ? 0 : 1][obj.sub] || subsystems[+!colors].default
  if (colors) {
    return ' \033[' + levels[type] + 'm' + (pad(type)) + '\033[39m ' + sub + ' ' + finalmsg
  } else {
    return ' ' + (pad(type)) + ' ' + sub + ' ' + finalmsg
  }
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/middleware.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/middleware.js

Statements: 13.51% (15 / 111)      Branches: 0% (0 / 63)      Functions: 0% (0 / 21)      Lines: 14.29% (15 / 105)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 2061 1 1 1   1                   1                     1                     1                     1             1                                     1       1                                       1                                                                                 1                                                         1                                                                          
var crypto = require('crypto')
var Error  = require('http-errors')
var utils  = require('./utils')
var Logger = require('./logger')
 
module.exports.match = function match(regexp) {
  return function(req, res, next, value, name) {
    if (regexp.exec(value)) {
      next()
    } else {
      next('route')
    }
  }
}
 
module.exports.validate_name = function validate_name(req, res, next, value, name) {
  if (value.charAt(0) === '-') {
    // special case in couchdb usually
    next('route')
  } else if (utils.validate_name(value)) {
    next()
  } else {
    next( Error[403]('invalid ' + name) )
  }
}
 
module.exports.validate_package = function validate_package(req, res, next, value, name) {
  if (value.charAt(0) === '-') {
    // special case in couchdb usually
    next('route')
  } else if (utils.validate_package(value)) {
    next()
  } else {
    next( Error[403]('invalid ' + name) )
  }
}
 
module.exports.media = function media(expect) {
  return function(req, res, next) {
    if (req.headers['content-type'] !== expect) {
      next( Error[415]('wrong content-type, expect: ' + expect
                     + ', got: '+req.headers['content-type']) )
    } else {
      next()
    }
  }
}
 
module.exports.expect_json = function expect_json(req, res, next) {
  if (!utils.is_object(req.body)) {
    return next( Error[400]("can't parse incoming json") )
  }
  next()
}
 
module.exports.anti_loop = function(config) {
  return function(req, res, next) {
    if (req.headers.via != null) {
      var arr = req.headers.via.split(',')
 
      for (var i=0; i<arr.length; i++) {
        var m = arr[i].match(/\s*(\S+)\s+(\S+)/)
        if (m && m[2] === config.server_id) {
          return next( Error[508]('loop detected') )
        }
      }
    }
    next()
  }
}
 
// express doesn't do etags with requests <= 1024b
// we use md5 here, it works well on 1k+ bytes, but sucks with fewer data
// could improve performance using crc32 after benchmarks
function md5sum(data) {
  return crypto.createHash('md5').update(data).digest('hex')
}
 
module.exports.allow = function(auth) {
  return function(action) {
    return function(req, res, next) {
      req.pause();
      auth['allow_'+action](req.params.package, req.remote_user, function(error, is_allowed) {
        req.resume();
        if (error) {
          next(error)
        } else if (is_allowed) {
          next()
        } else {
          // last plugin (that's our built-in one) returns either
          // cb(err) or cb(null, true), so this should never happen
          throw Error('bug in the auth plugin system')
        }
      })
    }
  }
}
 
module.exports.final = function(body, req, res, next) {
  if (res.statusCode === 401 && !res.getHeader('WWW-Authenticate')) {
    // they say it's required for 401, so...
    res.header('WWW-Authenticate', 'Basic, Bearer')
  }
 
  try {
    if (typeof(body) === 'string' || typeof(body) === 'object') {
      if (!res.getHeader('Content-type')) {
        res.header('Content-type', 'application/json')
      }
 
      if (typeof(body) === 'object' && body != null) {
        if (typeof(body.error) === 'string') {
          res._sinopia_error = body.error
        }
        body = JSON.stringify(body, undefined, '  ') + '\n'
      }
 
      // don't send etags with errors
      if (!res.statusCode || (res.statusCode >= 200 && res.statusCode < 300)) {
        res.header('ETag', '"' + md5sum(body) + '"')
      }
    } else {
      // send(null), send(204), etc.
    }
  } catch(err) {
    // if sinopia sends headers first, and then calls res.send()
    // as an error handler, we can't report error properly,
    // and should just close socket
    if (err.message.match(/set headers after they are sent/)) {
      if (res.socket != null) res.socket.destroy()
      return
    } else {
      throw err
    }
  }
 
  res.send(body)
}
 
module.exports.log = function(req, res, next) {
  // logger
  req.log = Logger.logger.child({ sub: 'in' })
 
  var _auth = req.headers.authorization
  if (_auth != null) req.headers.authorization = '<Classified>'
  var _cookie = req.headers.cookie
  if (_cookie != null) req.headers.cookie = '<Classified>'
 
  req.url = req.originalUrl
  req.log.info( { req: req, ip: req.ip }
              , '@{ip} requested \'@{req.method} @{req.url}\'' )
  req.originalUrl = req.url
 
  if (_auth != null) req.headers.authorization = _auth
  if (_cookie != null) req.headers.cookie = _cookie
 
  var bytesin = 0
  req.on('data', function(chunk) {
    bytesin += chunk.length
  })
 
  var bytesout = 0
  var _write = res.write
  res.write = function(buf) {
    bytesout += buf.length
    _write.apply(res, arguments)
  }
 
  function log() {
    var message = "@{status}, user: @{user}, req: '@{request.method} @{request.url}'"
    if (res._sinopia_error) {
      message += ', error: @{!error}'
    } else {
      message += ', bytes: @{bytes.in}/@{bytes.out}'
    }
 
    req.url = req.originalUrl
    req.log.warn({
      request : { method: req.method, url: req.url },
      level   : 35, // http
      user    : req.remote_user && req.remote_user.name,
      status  : res.statusCode,
      error   : res._sinopia_error,
      bytes   : {
        in  : bytesin,
        out : bytesout,
      }
    }, message)
    req.originalUrl = req.url
  }
 
  req.on('close', function() {
    log(true)
  })
 
  var _end = res.end
  res.end = function(buf) {
    if (buf) bytesout += buf.length
    _end.apply(res, arguments)
    log()
  }
  next()
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/plugin-loader.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/plugin-loader.js

Statements: 15.38% (4 / 26)      Branches: 0% (0 / 22)      Functions: 0% (0 / 3)      Lines: 15.38% (4 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 531   1                     1                                                                         1    
var Path = require('path')
 
function try_load(path) {
  try {
    return require(path)
  } catch(err) {
    if (err.code === 'MODULE_NOT_FOUND') {
      return null
    }
    throw err
  }
}
 
function load_plugins(config, plugin_configs, params, sanity_check) {
  var plugins = Object.keys(plugin_configs || {}).map(function(p) {
    var plugin
 
    // npm package
    if (plugin == null && p.match(/^[^\.\/]/)) {
      plugin = try_load('sinopia-' + p)
    }
 
    if (plugin == null) {
      plugin = try_load(p)
    }
 
    // relative to config path
    if (plugin == null && p.match(/^\.\.?($|\/)/)) {
      plugin = try_load(Path.resolve(Path.dirname(config.self_path), p))
    }
 
    if (plugin == null) {
      throw Error('"' + p + '" plugin not found\n'
        + 'try "npm install sinopia-' + p + '"')
    }
 
    if (typeof(plugin) !== 'function')
      throw Error('"' + p + '" doesn\'t look like a valid plugin')
 
    plugin = plugin(plugin_configs[p], params)
 
    if (plugin == null || !sanity_check(plugin))
      throw Error('"' + p + '" doesn\'t look like a valid plugin')
 
    return plugin
  })
 
  return plugins
}
 
exports.load_plugins = load_plugins;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/search.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/search.js

Statements: 53.85% (14 / 26)      Branches: 0% (0 / 4)      Functions: 25% (2 / 8)      Lines: 56% (14 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501   1 1 1 1 1 1 1   1     1       1                         1                     1         1      
var lunr = require('lunr')
 
function Search() {
  var self = Object.create(Search.prototype)
  self.index = lunr(function() {
    this.field('name'        , { boost: 10 })
    this.field('description' , { boost:  4 })
    this.field('author'      , { boost:  6 })
    this.field('readme')
  })
  return self
}
 
Search.prototype.query = function(q) {
  return this.index.search(q)
}
 
Search.prototype.add = function(package) {
  this.index.add({
    id:           package.name,
    name:         package.name,
    description:  package.description,
    author:       package._npmUser ? package._npmUser.name : '???',
  })
},
 
Search.prototype.remove = function(name) {
  this.index.remove({ id: name })
}
 
Search.prototype.reindex = function() {
  var self = this
  this.storage.get_local(function(err, packages) {
    if (err) throw err // that function shouldn't produce any
    var i = packages.length
    while (i--) {
      self.add(packages[i])
    }
  })
}
 
Search.prototype.configureStorage = function(storage) {
  this.storage = storage
  this.reindex()
}
 
module.exports = Search()
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/status-cats.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/status-cats.js

Statements: 27.27% (3 / 11)      Branches: 0% (0 / 4)      Functions: 0% (0 / 3)      Lines: 27.27% (3 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76      1                                                                                                       1             1                          
 
// see https://secure.flickr.com/photos/girliemac/sets/72157628409467125
 
var images = {
  100: 'aVvDhR', // '6512768893', // 100 - Continue
  101: 'aXXExP', // '6540479029', // 101 - Switching Protocols
  200: 'aVuVsF', // '6512628175', // 200 - OK
  201: 'aXWm1Z', // '6540221577', // 201 - Created
  202: 'aXXEyF', // '6540479079', // 202 - Accepted
  204: 'aYyJ7B', // '6547319943', // 204 - No Content
  206: 'aVEnUP', // '6514473163', // 206 - Partial Content
  207: 'aVEnRD', // '6514472979', // 207 - Multi-Status
  300: 'aW7mac', // '6519540181', // 300 - Multiple Choices
  301: 'aW7mb4', // '6519540231', // 301 - Moved Permanently
  302: 'aV6jKp', // '6508023829', // 302 - Found
  303: 'aVxtaK', // '6513125065', // 303 - See Other
  304: 'aXY3dH', // '6540551929', // 304 - Not Modified
  305: 'aXX5LK', // '6540365403', // 305 - Use Proxy
  307: 'aVwQnk', // '6513001269', // 307 - Temporary Redirect
  400: 'aXYDeT', // '6540669737', // 400 - Bad Request
  401: 'aV6jwe', // '6508023065', // 401 - Unauthorized
  402: 'aVwQoe', // '6513001321', // 402 - Payment Required
  403: 'aV6jFK', // '6508023617', // 403 - Forbidden
  404: 'aV6juR', // '6508022985', // 404 - Not Found
  405: 'aV6jE8', // '6508023523', // 405 - Method Not Allowed
  406: 'aV6jxa', // '6508023119', // 406 - Not Acceptable
  408: 'aV6jyc', // '6508023179', // 408 - Request Timeout
  409: 'aV6jzz', // '6508023259', // 409 - Conflict
  410: 'aVES2H', // '6514567755', // 410 - Gone
  411: 'aXYVpT', // '6540724141', // 411 - Length Required
  413: 'aV6jHZ', // '6508023747', // 413 - Request Entity Too Large
  414: 'aV6jBa', // '6508023351', // 414 - Request-URI Too Long
  416: 'aVxQvr', // '6513196851', // 416 - Requested Range Not Satisfiable
  417: 'aV6jGP', // '6508023679', // 417 - Expectation Failed
  418: 'aV6J7c', // '6508102407', // 418 - I'm a teapot
  422: 'aVEnTt', // '6514473085', // 422 - Unprocessable Entity
  423: 'aVEyVZ', // '6514510235', // 423 - Locked
  424: 'aVEWZ6', // '6514584423', // 424 - Failed Dependency
  425: 'aXYdzH', // '6540586787', // 425 - Unordered Collection
  426: 'aVdo4M', // '6509400771', // 426 - Upgrade Required
  429: 'aVdo8F', // '6509400997', // 429 - Too Many Requests
  431: 'aVdo3n', // '6509400689', // 431 - Request Header Fields Too Large
  444: 'aVdo1P', // '6509400599', // 444 - No Response
  450: 'aVxtbK', // '6513125123', // 450 - Blocked by Windows Parental Controls
  451: 'eTiGQd', // '9113233540', // 451 - Unavailable for Legal Reasons
  500: 'aVdo6e', // '6509400855', // 500 - Internal Server Error
  502: 'aV6jCv', // '6508023429', // 502 - Bad Gateway
  503: 'aXYvop', // '6540643319', // 503 - Service Unavailable
  506: 'aXYvnH', // '6540643279', // 506 - Variant Also Negotiates
  507: 'aVdnZa', // '6509400503', // 507 - Insufficient Storage
  508: 'aVdnYa', // '6509400445', // 508 - Loop Detected
  509: 'aXXg1V', // '6540399865', // 509 - Bandwidth Limit Exceeded
  599: 'aVdo7v', // '6509400929', // 599 - Network connect timeout error
}
 
module.exports.get_image = function(status) {
  if (status in images) {
    return 'http://flic.kr/p/' + images[status]
    //return 'https://secure.flickr.com/photos/girliemac/'+images[status]+'/in/set-72157628409467125/lightbox/'
  }
}
 
module.exports.middleware = function(req, res, next) {
  var _writeHead = res.writeHead
  res.writeHead = function(status) {
    if (status in images) {
      res.setHeader('X-Status-Cat', module.exports.get_image(status))
    }
    _writeHead.apply(res, arguments)
  }
 
  next()
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/storage.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/storage.js

Statements: 11.98% (29 / 242)      Branches: 0% (0 / 118)      Functions: 0% (0 / 55)      Lines: 13.18% (29 / 220)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 5331 1 1 1 1 1 1 1 1   1           1                                                 1                                         1                   1                                           1                   1                 1                 1                       1                     1                         1                     1                           1                                                                                                     1                                                                                                                 1                                                                                                 1                                                                       1                                                                         1                                                                                                                                                                                                     1                                        
var assert    = require('assert')
var async     = require('async')
var Error     = require('http-errors')
var Stream    = require('stream')
var Local     = require('./local-storage')
var Logger    = require('./logger')
var MyStreams = require('./streams')
var Proxy     = require('./up-storage')
var Utils     = require('./utils')
 
module.exports = Storage
 
//
// Implements Storage interface
// (same for storage.js, local-storage.js, up-storage.js)
//
function Storage(config) {
  var self = Object.create(Storage.prototype)
  self.config = config
 
  // we support a number of uplinks, but only one local storage
  // Proxy and Local classes should have similar API interfaces
  self.uplinks = {}
  for (var p in config.uplinks) {
    self.uplinks[p] = Proxy(config.uplinks[p], config)
    self.uplinks[p].upname = p
  }
  self.local = Local(config)
  self.logger = Logger.logger.child()
 
  return self
}
 
//
// Add a {name} package to a system
//
// Function checks if package with the same name is available from uplinks.
// If it isn't, we create package locally
//
// Used storages: local (write) && uplinks
//
Storage.prototype.add_package = function(name, metadata, callback) {
  var self = this
 
  // NOTE:
  // - when we checking package for existance, we ask ALL uplinks
  // - when we publishing package, we only publish it to some of them
  // so all requests are necessary
 
  check_package_local(function(err) {
    if (err) return callback(err)
 
    check_package_remote(function(err) {
      if (err) return callback(err)
 
      publish_package(function(err) {
        if (err) return callback(err)
        callback()
      })
    })
  })
 
  function check_package_local(cb) {
    self.local.get_package(name, {}, function(err, results) {
      if (err && err.status !== 404) return cb(err)
 
      if (results) return cb( Error[409]('this package is already present') )
 
      cb()
    })
  }
 
  function check_package_remote(cb) {
    self._sync_package_with_uplinks(name, null, {}, function(err, results, err_results) {
      // something weird
      if (err && err.status !== 404) return cb(err)
 
      // checking package
      if (results) return cb( Error[409]('this package is already present') )
 
      for (var i=0; i<err_results.length; i++) {
        // checking error
        // if uplink fails with a status other than 404, we report failure
        if (err_results[i][0] != null) {
          if (err_results[i][0].status !== 404) {
            return cb( Error[503]('one of the uplinks is down, refuse to publish') )
          }
        }
      }
 
      return cb()
    })
  }
 
  function publish_package(cb) {
    self.local.add_package(name, metadata, callback)
  }
}
 
//
// Add a new version of package {name} to a system
//
// Used storages: local (write)
//
Storage.prototype.add_version = function(name, version, metadata, tag, callback) {
  return this.local.add_version(name, version, metadata, tag, callback)
}
 
//
// Tags a package version with a provided tag
//
// Used storages: local (write)
//
Storage.prototype.merge_tags = function(name, tag_hash, callback) {
  return this.local.merge_tags(name, tag_hash, callback)
}
 
//
// Tags a package version with a provided tag
//
// Used storages: local (write)
//
Storage.prototype.replace_tags = function(name, tag_hash, callback) {
  return this.local.replace_tags(name, tag_hash, callback)
}
 
//
// Change an existing package (i.e. unpublish one version)
//
// Function changes a package info from local storage and all uplinks with
// write access.
//
// Used storages: local (write)
//
Storage.prototype.change_package = function(name, metadata, revision, callback) {
  return this.local.change_package(name, metadata, revision, callback)
}
 
//
// Remove a package from a system
//
// Function removes a package from local storage
//
// Used storages: local (write)
//
Storage.prototype.remove_package = function(name, callback) {
  return this.local.remove_package(name, callback)
}
 
//
// Remove a tarball from a system
//
// Function removes a tarball from local storage.
// Tarball in question should not be linked to in any existing
// versions, i.e. package version should be unpublished first.
//
// Used storages: local (write)
//
Storage.prototype.remove_tarball = function(name, filename, revision, callback) {
  return this.local.remove_tarball(name, filename, revision, callback)
}
 
//
// Upload a tarball for {name} package
//
// Function is syncronous and returns a WritableStream
//
// Used storages: local (write)
//
Storage.prototype.add_tarball = function(name, filename) {
  return this.local.add_tarball(name, filename)
}
 
//
// Get a tarball from a storage for {name} package
//
// Function is syncronous and returns a ReadableStream
//
// Function tries to read tarball locally, if it fails then it reads package
// information in order to figure out where we can get this tarball from
//
// Used storages: local || uplink (just one)
//
Storage.prototype.get_tarball = function(name, filename) {
  var stream = MyStreams.ReadTarballStream()
  stream.abort = function() {}
 
  var self = this
 
  // if someone requesting tarball, it means that we should already have some
  // information about it, so fetching package info is unnecessary
 
  // trying local first
  var rstream = self.local.get_tarball(name, filename)
  var is_open = false
  rstream.on('error', function(err) {
    if (is_open || err.status !== 404) {
      return stream.emit('error', err)
    }
 
    // local reported 404
    var err404 = err
    rstream.abort()
    rstream = null // gc
 
    self.local.get_package(name, function(err, info) {
      if (!err && info._distfiles && info._distfiles[filename] != null) {
        // information about this file exists locally
        serve_file(info._distfiles[filename])
 
      } else {
        // we know nothing about this file, trying to get information elsewhere
 
        self._sync_package_with_uplinks(name, info, {}, function(err, info) {
          if (err) return stream.emit('error', err)
 
          if (!info._distfiles || info._distfiles[filename] == null) {
            return stream.emit('error', err404)
          }
 
          serve_file(info._distfiles[filename])
        })
      }
    })
  })
  rstream.on('content-length', function(v) {
    stream.emit('content-length', v)
  })
  rstream.on('open', function() {
    is_open = true
    rstream.pipe(stream)
  })
  return stream
 
  function serve_file(file) {
    var uplink = null
    for (var p in self.uplinks) {
      if (self.uplinks[p].can_fetch_url(file.url)) {
        uplink = self.uplinks[p]
      }
    }
    if (uplink == null) {
      uplink = Proxy({
        url: file.url,
        _autogenerated: true,
      }, self.config)
    }
 
    var savestream = self.local.add_tarball(name, filename)
    var on_open = function() {
      on_open = function(){} // prevent it from being called twice
      var rstream2 = uplink.get_url(file.url)
      rstream2.on('error', function(err) {
        if (savestream) savestream.abort()
        savestream = null
        stream.emit('error', err)
      })
      rstream2.on('end', function() {
        if (savestream) savestream.done()
      })
 
      rstream2.on('content-length', function(v) {
        stream.emit('content-length', v)
        if (savestream) savestream.emit('content-length', v)
      })
      rstream2.pipe(stream)
      if (savestream) rstream2.pipe(savestream)
    }
 
    savestream.on('open', function() {
      on_open()
    })
    savestream.on('error', function(err) {
      self.logger.warn( { err: err }
                      , 'error saving file: @{err.message}\n@{err.stack}' )
      if (savestream) savestream.abort()
      savestream = null
      on_open()
    })
  }
}
 
//
// Retrieve a package metadata for {name} package
//
// Function invokes local.get_package and uplink.get_package for every
// uplink with proxy_access rights against {name} and combines results
// into one json object
//
// Used storages: local && uplink (proxy_access)
//
Storage.prototype.get_package = function(name, options, callback) {
  if (typeof(options) === 'function') callback = options, options = {}
 
  var self = this
 
  self.local.get_package(name, options, function(err, data) {
    if (err && (!err.status || err.status >= 500)) {
      // report internal errors right away
      return callback(err)
    }
 
    self._sync_package_with_uplinks(name, data, options, function(err, result, uplink_errors) {
      if (err) return callback(err)
      var whitelist = [ '_rev', 'name', 'versions', 'dist-tags', 'readme' ]
      for (var i in result) {
        if (whitelist.indexOf(i) === -1) delete result[i]
      }
 
      if (self.config.ignore_latest_tag || !result['dist-tags'].latest) {
        result['dist-tags'].latest = Utils.semver_sort(Object.keys(result.versions))
      }
 
      for (var i in result['dist-tags']) {
        if (Array.isArray(result['dist-tags'][i])) {
          result['dist-tags'][i] = result['dist-tags'][i][result['dist-tags'][i].length-1]
          if (result['dist-tags'][i] == null) delete result['dist-tags'][i]
        }
      }
 
      // npm can throw if this field doesn't exist
      result._attachments = {}
 
      callback(null, result, uplink_errors)
    })
  })
}
 
//
// Retrieve remote and local packages more recent than {startkey}
//
// Function streams all packages from all uplinks first, and then
// local packages.
//
// Note that local packages could override registry ones just because
// they appear in JSON last. That's a trade-off we make to avoid
// memory issues.
//
// Used storages: local && uplink (proxy_access)
//
Storage.prototype.search = function(startkey, options) {
  var self = this
 
  var stream = new Stream.PassThrough({ objectMode: true })
 
  async.eachSeries(Object.keys(self.uplinks), function(up_name, cb) {
    // shortcut: if `local=1` is supplied, don't call uplinks
    if (options.req.query.local !== undefined) return cb()
 
    var lstream = self.uplinks[up_name].search(startkey, options)
    lstream.pipe(stream, { end: false })
    lstream.on('error', function (err) {
      self.logger.error({ err: err }, 'uplink error: @{err.message}')
      cb(), cb = function () {}
    })
    lstream.on('end', function () {
      cb(), cb = function () {}
    })
 
    stream.abort = function () {
      if (lstream.abort) lstream.abort()
      cb(), cb = function () {}
    }
  }, function () {
    var lstream = self.local.search(startkey, options)
    stream.abort = function () { lstream.abort() }
    lstream.pipe(stream, { end: true })
    lstream.on('error', function (err) {
      self.logger.error({ err: err }, 'search error: @{err.message}')
      stream.end()
    })
  })
 
  return stream
}
 
Storage.prototype.get_local = function(callback) {
  var self = this
  var locals = this.config.localList.get()
  var packages = []
 
  var getPackage = function(i) {
    self.local.get_package(locals[i], function(err, info) {
      if (!err) {
        var latest = Array.isArray(info['dist-tags'].latest)
                   ? Utils.semver_sort(info['dist-tags'].latest).pop()
                   : info['dist-tags'].latest
        if (info.versions[latest]) {
          packages.push(info.versions[latest])
        } else {
          self.logger.warn( { package: locals[i] }
                          , 'package @{package} does not have a "latest" tag?' )
        }
      }
 
      if (i >= locals.length - 1) {
        callback(null, packages)
      } else {
        getPackage(i + 1)
      }
    })
  }
 
  if (locals.length) {
    getPackage(0)
  } else {
    callback(null, [])
  }
}
 
// function fetches package information from uplinks and synchronizes it with local data
// if package is available locally, it MUST be provided in pkginfo
// returns callback(err, result, uplink_errors)
Storage.prototype._sync_package_with_uplinks = function(name, pkginfo, options, callback) {
  var self = this
 
  if (!pkginfo) {
    var exists = false
 
    pkginfo = {
      name        : name,
      versions    : {},
      'dist-tags' : {},
      _uplinks    : {},
    }
  } else {
    var exists = true
  }
 
  var uplinks = []
  for (var i in self.uplinks) {
    if (self.config.can_proxy_to(name, i)) {
      uplinks.push(self.uplinks[i])
    }
  }
 
  async.map(uplinks, function(up, cb) {
    var _options = Object.assign({}, options)
    if (Utils.is_object(pkginfo._uplinks[up.upname])) {
      var fetched = pkginfo._uplinks[up.upname].fetched
      if (fetched && fetched > (Date.now() - up.maxage)) {
        return cb()
      }
 
      _options.etag = pkginfo._uplinks[up.upname].etag
    }
 
    up.get_package(name, _options, function(err, up_res, etag) {
      if (err && err.status === 304)
        pkginfo._uplinks[up.upname].fetched = Date.now()
 
      if (err || !up_res) return cb(null, [err || Error('no data')])
 
      try {
        Utils.validate_metadata(up_res, name)
      } catch(err) {
        self.logger.error({
          sub: 'out',
          err: err,
        }, 'package.json validating error @{!err.message}\n@{err.stack}')
        return cb(null, [ err ])
      }
 
      pkginfo._uplinks[up.upname] = {
        etag: etag,
        fetched: Date.now()
      }
 
      for (var i in up_res.versions) {
        // this won't be serialized to json,
        // kinda like an ES6 Symbol
        Object.defineProperty(up_res.versions[i], '_sinopia_uplink', {
          value        : up.upname,
          enumerable   : false,
          configurable : false,
          writable     : true,
        })
      }
 
      try {
        Storage._merge_versions(pkginfo, up_res, self.config)
      } catch(err) {
        self.logger.error({
          sub: 'out',
          err: err,
        }, 'package.json parsing error @{!err.message}\n@{err.stack}')
        return cb(null, [ err ])
      }
 
      // if we got to this point, assume that the correct package exists
      // on the uplink
      exists = true
      cb()
    })
  }, function(err, uplink_errors) {
    assert(!err && Array.isArray(uplink_errors))
 
    if (!exists) {
      return callback( Error[404]('no such package available')
                     , null
                     , uplink_errors )
    }
 
    self.local.update_versions(name, pkginfo, function(err, pkginfo) {
      if (err) return callback(err)
      return callback(null, pkginfo, uplink_errors)
    })
  })
}
 
// function gets a local info and an info from uplinks and tries to merge it
// exported for unit tests only
Storage._merge_versions = function(local, up, config) {
  // copy new versions to a cache
  // NOTE: if a certain version was updated, we can't refresh it reliably
  for (var i in up.versions) {
    if (local.versions[i] == null) {
      local.versions[i] = up.versions[i]
    }
  }
 
  // refresh dist-tags
  for (var i in up['dist-tags']) {
    var added = Utils.tag_version(local, up['dist-tags'][i], i, config || {})
    if (i === 'latest' && added) {
      // if remote has more fresh package, we should borrow its readme
      local.readme = up.readme
    }
  }
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/streams.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/streams.js

Statements: 32.14% (9 / 28)      Branches: 0% (0 / 6)      Functions: 0% (0 / 6)      Lines: 32.14% (9 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 621 1   1 1         1                   1         1                         1           1                                    
var Stream = require('stream')
var Util   = require('util')
 
module.exports.ReadTarballStream = ReadTarball
module.exports.UploadTarballStream = UploadTarball
 
//
// This stream is used to read tarballs from repository
//
function ReadTarball(options) {
  var self = new Stream.PassThrough(options)
  Object.setPrototypeOf(self, ReadTarball.prototype)
 
  // called when data is not needed anymore
  add_abstract_method(self, 'abort')
 
  return self
}
 
Util.inherits(ReadTarball, Stream.PassThrough)
 
//
// This stream is used to upload tarballs to a repository
//
function UploadTarball(options) {
  var self = new Stream.PassThrough(options)
  Object.setPrototypeOf(self, UploadTarball.prototype)
 
  // called when user closes connection before upload finishes
  add_abstract_method(self, 'abort')
 
  // called when upload finishes successfully
  add_abstract_method(self, 'done')
 
  return self
}
 
Util.inherits(UploadTarball, Stream.PassThrough)
 
//
// This function intercepts abstract calls and replays them allowing
// us to attach those functions after we are ready to do so
//
function add_abstract_method(self, name) {
  self._called_methods = self._called_methods || {}
  self.__defineGetter__(name, function() {
    return function() {
      self._called_methods[name] = true
    }
  })
  self.__defineSetter__(name, function(fn) {
    delete self[name]
    self[name] = fn
    if (self._called_methods && self._called_methods[name]) {
      delete self._called_methods[name]
      self[name]()
    }
  })
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/up-storage.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/up-storage.js

Statements: 11.82% (24 / 203)      Branches: 0% (0 / 145)      Functions: 0% (0 / 30)      Lines: 12.24% (24 / 196)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 3891 1 1 1 1 1 1 1 1 1   1           1                                                         1         1                                                                                         1                                                                                 1                                             1                                                                                                                   1                                               1               1                                                       1         1                                                                               1                                                                           1                                                      
var JSONStream     = require('JSONStream')
var Error          = require('http-errors')
var request        = require('request')
var Stream         = require('readable-stream')
var URL            = require('url')
var parse_interval = require('./config').parse_interval
var Logger         = require('./logger')
var MyStreams      = require('./streams')
var Utils          = require('./utils')
var encode         = encodeURIComponent
 
module.exports = Storage
 
//
// Implements Storage interface
// (same for storage.js, local-storage.js, up-storage.js)
//
function Storage(config, mainconfig) {
  var self = Object.create(Storage.prototype)
  self.config = config
  self.failed_requests = 0
  self.userAgent = mainconfig.user_agent
  self.ca = config.ca
  self.logger = Logger.logger.child({sub: 'out'})
  self.server_id = mainconfig.server_id
 
  self.url = URL.parse(self.config.url)
 
  _setupProxy.call(self, self.url.hostname, config, mainconfig, self.url.protocol === 'https:')
 
  self.config.url = self.config.url.replace(/\/$/, '')
  if (Number(self.config.timeout) >= 1000) {
    self.logger.warn([ 'Too big timeout value: ' + self.config.timeout,
                       'We changed time format to nginx-like one',
                       '(see http://wiki.nginx.org/ConfigNotation)',
                       'so please update your config accordingly' ].join('\n'))
  }
 
  // a bunch of different configurable timers
  self.maxage       = parse_interval(config_get('maxage'      , '2m' ))
  self.timeout      = parse_interval(config_get('timeout'     , '30s'))
  self.max_fails    =         Number(config_get('max_fails'   ,  2   ))
  self.fail_timeout = parse_interval(config_get('fail_timeout', '5m' ))
  return self
 
  // just a helper (`config[key] || default` doesn't work because of zeroes)
  function config_get(key, def) {
    return config[key] != null ? config[key] : def
  }
}
 
function _setupProxy(hostname, config, mainconfig, isHTTPS) {
  var no_proxy
  var proxy_key = isHTTPS ? 'https_proxy' : 'http_proxy'
 
  // get http_proxy and no_proxy configs
  if (proxy_key in config) {
    this.proxy = config[proxy_key]
  } else if (proxy_key in mainconfig) {
    this.proxy = mainconfig[proxy_key]
  }
  if ('no_proxy' in config) {
    no_proxy = config.no_proxy
  } else if ('no_proxy' in mainconfig) {
    no_proxy = mainconfig.no_proxy
  }
 
  // use wget-like algorithm to determine if proxy shouldn't be used
  if (hostname[0] !== '.') hostname = '.' + hostname
  if (typeof(no_proxy) === 'string' && no_proxy.length) {
    no_proxy = no_proxy.split(',')
  }
  if (Array.isArray(no_proxy)) {
    for (var i=0; i<no_proxy.length; i++) {
      var no_proxy_item = no_proxy[i]
      if (no_proxy_item[0] !== '.') no_proxy_item = '.' + no_proxy_item
      if (hostname.lastIndexOf(no_proxy_item) === hostname.length - no_proxy_item.length) {
        if (this.proxy) {
          this.logger.debug({url: this.url.href, rule: no_proxy_item},
            'not using proxy for @{url}, excluded by @{rule} rule')
          this.proxy = false
        }
        break
      }
    }
  }
 
  // if it's non-string (i.e. "false"), don't use it
  if (typeof(this.proxy) !== 'string') {
    delete this.proxy
  } else {
    this.logger.debug( { url: this.url.href, proxy: this.proxy }
                     , 'using proxy @{proxy} for @{url}' )
  }
}
 
Storage.prototype.request = function(options, cb) {
  if (!this.status_check()) {
    var req = new Stream.Readable()
    process.nextTick(function() {
      if (typeof(cb) === 'function') cb(Error('uplink is offline'))
      req.emit('error', Error('uplink is offline'))
    })
    // preventing 'Uncaught, unspecified "error" event'
    req.on('error', function(){})
    return req
  }
 
  var self = this
  var headers = options.headers || {}
  headers['Accept']          = headers['Accept']          || 'application/json'
  headers['Accept-Encoding'] = headers['Accept-Encoding'] || 'gzip'
  headers['User-Agent']      = headers['User-Agent']      || this.userAgent
  this._add_proxy_headers(options.req, headers)
 
  var method = options.method   || 'GET'
  var uri    = options.uri_full || (this.config.url + options.uri)
 
  self.logger.info({
    method  : method,
    headers : headers,
    uri     : uri,
  }, "making request: '@{method} @{uri}'")
 
  if (Utils.is_object(options.json)) {
    var json = JSON.stringify(options.json)
    headers['Content-Type'] = headers['Content-Type'] || 'application/json'
  }
 
  var request_callback = cb ? (function (err, res, body) {
    var error
    var res_length = err ? 0 : body.length
 
    do_decode()
    do_log()
    cb(err, res, body)
 
    function do_decode() {
      if (err) {
        error = err.message
        return
      }
 
      if (options.json && res.statusCode < 300) {
        try {
          body = JSON.parse(body.toString('utf8'))
        } catch(_err) {
          body = {}
          err = _err
          error = err.message
        }
      }
 
      if (!err && Utils.is_object(body)) {
        if (typeof(body.error) === 'string') {
          error = body.error
        }
      }
    }
 
    function do_log() {
      var message = '@{!status}, req: \'@{request.method} @{request.url}\''
      message += error
               ? ', error: @{!error}'
               : ', bytes: @{bytes.in}/@{bytes.out}'
      self.logger.warn({
        err     : err,
        request : { method: method, url: uri },
        level   : 35, // http
        status  : res != null ? res.statusCode : 'ERR',
        error   : error,
        bytes   : {
          in  : json ? json.length : 0,
          out : res_length || 0,
        }
      }, message)
    }
  }) : undefined
 
  var req = request({
    url      : uri,
    method   : method,
    headers  : headers,
    body     : json,
    ca       : this.ca,
    proxy    : this.proxy,
    encoding : null,
    gzip     : true,
    timeout  : this.timeout,
  }, request_callback)
 
  var status_called = false
  req.on('response', function(res) {
    if (!req._sinopia_aborted && !status_called) {
      status_called = true
      self.status_check(true)
    }
 
    if (!request_callback) {
      ;(function do_log() {
        var message = '@{!status}, req: \'@{request.method} @{request.url}\' (streaming)'
        self.logger.warn({
          request : { method: method, url: uri },
          level   : 35, // http
          status  : res != null ? res.statusCode : 'ERR',
        }, message)
      })()
    }
  })
  req.on('error', function(_err) {
    if (!req._sinopia_aborted && !status_called) {
      status_called = true
      self.status_check(false)
    }
  })
  return req
}
 
Storage.prototype.status_check = function(alive) {
  if (arguments.length === 0) {
    if (this.failed_requests >= this.max_fails
     && Math.abs(Date.now() - this.last_request_time) < this.fail_timeout) {
      return false
    } else {
      return true
    }
  } else {
    if (alive) {
      if (this.failed_requests >= this.max_fails) {
        this.logger.warn({ host: this.url.host }, 'host @{host} is back online')
      }
      this.failed_requests = 0
    } else {
      this.failed_requests++
      if (this.failed_requests === this.max_fails) {
        this.logger.warn({ host: this.url.host }, 'host @{host} is now offline')
      }
    }
    this.last_request_time = Date.now()
  }
}
 
Storage.prototype.can_fetch_url = function(url) {
  url = URL.parse(url)
 
  return url.protocol === this.url.protocol
      && url.host === this.url.host
      && url.path.indexOf(this.url.path) === 0
}
 
Storage.prototype.get_package = function(name, options, callback) {
  if (typeof(options) === 'function') callback = options, options = {}
 
  var headers = {}
  if (options.etag) {
    headers['If-None-Match'] = options.etag
    headers['Accept']        = 'application/octet-stream'
  }
 
  this.request({
    uri     : '/' + encode(name),
    json    : true,
    headers : headers,
    req     : options.req,
  }, function(err, res, body) {
    if (err) return callback(err)
    if (res.statusCode === 404) {
      return callback( Error[404]("package doesn't exist on uplink") )
    }
    if (!(res.statusCode >= 200 && res.statusCode < 300)) {
      var error = Error('bad status code: ' + res.statusCode)
      error.remoteStatus = res.statusCode
      return callback(error)
    }
    callback(null, body, res.headers.etag)
  })
}
 
Storage.prototype.get_tarball = function(name, options, filename) {
  if (!options) options = {}
  return this.get_url(this.config.url + '/' + name + '/-/' + filename)
}
 
Storage.prototype.get_url = function(url) {
  var stream = MyStreams.ReadTarballStream()
  stream.abort = function() {}
  var current_length = 0, expected_length
 
  var rstream = this.request({
    uri_full: url,
    encoding: null,
    headers: { Accept: 'application/octet-stream' },
  })
 
  rstream.on('response', function(res) {
    if (res.statusCode === 404) {
      return stream.emit('error', Error[404]("file doesn't exist on uplink"))
    }
    if (!(res.statusCode >= 200 && res.statusCode < 300)) {
      return stream.emit('error', Error('bad uplink status code: ' + res.statusCode))
    }
    if (res.headers['content-length']) {
      expected_length = res.headers['content-length']
      stream.emit('content-length', res.headers['content-length'])
    }
 
    rstream.pipe(stream)
  })
 
  rstream.on('error', function(err) {
    stream.emit('error', err)
  })
  rstream.on('data', function(d) {
    current_length += d.length
  })
  rstream.on('end', function(d) {
    if (d) current_length += d.length
    if (expected_length && current_length != expected_length)
      stream.emit('error', Error('content length mismatch'))
  })
  return stream
}
 
Storage.prototype.search = function(startkey, options) {
  var self = this
 
  var stream = new Stream.PassThrough({ objectMode: true })
 
  var req = self.request({
    uri: options.req.url,
    req: options.req,
  })
 
  req.on('response', function (res) {
    if (!String(res.statusCode).match(/^2\d\d$/)) {
      return stream.emit('error', Error('bad status code ' + res.statusCode + ' from uplink'))
    }
 
    res.pipe(JSONStream.parse('*')).on('data', function (pkg) {
      if (Utils.is_object(pkg)) {
        stream.emit('data', pkg)
      }
    })
 
    res.on('end', function () {
      stream.emit('end')
    })
  })
 
  req.on('error', function (err) {
    stream.emit('error', err)
  })
 
  stream.abort = function () {
    req.abort()
    stream.emit('end')
  }
 
  return stream
}
 
Storage.prototype._add_proxy_headers = function(req, headers) {
  if (req) {
    // Only submit X-Forwarded-For field if we don't have a proxy selected
    // in the config file.
    //
    // Otherwise misconfigured proxy could return 407:
    // https://github.com/rlidwka/sinopia/issues/254
    //
    if (!this.proxy) {
      headers['X-Forwarded-For'] = (
        req && req.headers['x-forwarded-for']
        ? req.headers['x-forwarded-for'] + ', '
        : ''
      ) + req.connection.remoteAddress
    }
  }
 
  // always attach Via header to avoid loops, even if we're not proxying
  headers['Via'] =
    req && req.headers['via']
    ? req.headers['via'] + ', '
    : ''
 
  headers['Via'] += '1.1 ' + this.server_id + ' (Sinopia)'
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/lib/utils.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/lib/utils.js

Statements: 18.29% (15 / 82)      Branches: 0% (0 / 63)      Functions: 0% (0 / 12)      Lines: 20.27% (15 / 74)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 1741 1 1 1   1                           1                                     1       1                             1 1                                               1           1                                         1                             1                                                                     1                            
var assert = require('assert')
var Semver = require('semver')
var URL    = require('url')
var Logger = require('./logger')
 
module.exports.validate_package = function(name) {
  name = name.split('/', 2)
  if (name.length === 1) {
    // normal package
    return module.exports.validate_name(name[0])
  } else {
    // scoped package
    return name[0][0] === '@'
        && module.exports.validate_name(name[0].slice(1))
        && module.exports.validate_name(name[1])
  }
}
 
// from normalize-package-data/lib/fixer.js
module.exports.validate_name = function(name) {
  if (typeof(name) !== 'string') return false
  name = name.toLowerCase()
 
  // all URL-safe characters and "@" for issue #75
  if (!name.match(/^[-a-zA-Z0-9_.!~*'()@]+$/)
   || name.charAt(0) === '.' // ".bin", etc.
   || name.charAt(0) === '-' // "-" is reserved by couchdb
   || name === 'node_modules'
   || name === '__proto__'
   || name === 'package.json'
   || name === 'favicon.ico'
  ) {
    return false
  } else {
    return true
  }
}
 
module.exports.is_object = function(obj) {
  return typeof(obj) === 'object' && obj !== null && !Array.isArray(obj)
}
 
module.exports.validate_metadata = function(object, name) {
  assert(module.exports.is_object(object), 'not a json object')
  assert.equal(object.name, name)
 
  if (!module.exports.is_object(object['dist-tags'])) {
    object['dist-tags'] = {}
  }
 
  if (!module.exports.is_object(object['versions'])) {
    object['versions'] = {}
  }
 
  return object
}
 
module.exports.filter_tarball_urls = function(pkg, req, config) {
  function filter(_url) {
    if (!req.headers.host) return _url
 
    var filename = URL.parse(_url).pathname.replace(/^.*\//, '')
 
    if (config.url_prefix != null) {
      var result = config.url_prefix.replace(/\/$/, '')
    } else {
      var result = req.protocol + '://' + req.headers.host
    }
 
    return result + '/' + pkg.name.replace(/\//g, '%2f') + '/-/' + filename
  }
 
  for (var ver in pkg.versions) {
    var dist = pkg.versions[ver].dist
    if (dist != null && dist.tarball != null) {
      //dist.__sinopia_orig_tarball = dist.tarball
      dist.tarball = filter(dist.tarball)
    }
  }
  return pkg
}
 
function can_add_tag(tag, config) {
  if (!tag) return false
  if (tag === 'latest' && config.ignore_latest_tag) return false
  return true
}
 
module.exports.tag_version = function(data, version, tag, config) {
  if (!can_add_tag(tag, config)) return false
 
  switch (typeof(data['dist-tags'][tag])) {
    case 'string':
      data['dist-tags'][tag] = [ data['dist-tags'][tag] ]
      break
    case 'object': // array
      break
    default:
      data['dist-tags'][tag] = []
  }
  if (data['dist-tags'][tag].indexOf(version) === -1) {
    data['dist-tags'][tag].push(version)
    data['dist-tags'][tag] = module.exports.semver_sort(data['dist-tags'][tag])
    return data['dist-tags'][tag][data['dist-tags'][tag].length - 1] === version
  }
  return false
}
 
// gets version from a package object taking into account semver weirdness
module.exports.get_version = function(object, version) {
  if (object.versions[version] != null) return object.versions[version]
 
  try {
    version = Semver.parse(version, true)
    for (var k in object.versions) {
      if (version.compare(Semver.parse(k, true)) === 0) {
        return object.versions[k]
      }
    }
  } catch (err) {
    return undefined
  }
}
 
module.exports.parse_address = function parse_address(addr) {
  //
  // Allow:
  //
  //  - https:localhost:1234        - protocol + host + port
  //  - localhost:1234              - host + port
  //  - 1234                        - port
  //  - http::1234                  - protocol + port
  //  - https://localhost:443/      - full url + https
  //  - http://[::1]:443/           - ipv6
  //  - unix:/tmp/http.sock         - unix sockets
  //  - https://unix:/tmp/http.sock - unix sockets (https)
  //
  // TODO: refactor it to something more reasonable?
  //
  //        protocol :  //      (  host  )|(    ipv6     ):  port  /
  var m = /^((https?):(\/\/)?)?((([^\/:]*)|\[([^\[\]]+)\]):)?(\d+)\/?$/.exec(addr)
 
  if (m) return {
    proto: m[2] || 'http',
    host:  m[6] || m[7] || 'localhost',
    port:  m[8] || '4873',
  }
 
  var m = /^((https?):(\/\/)?)?unix:(.*)$/.exec(addr)
 
  if (m) return {
    proto: m[2] || 'http',
    path:  m[4],
  }
 
  return null
}
 
// function filters out bad semver versions and sorts the array
module.exports.semver_sort = function semver_sort(array) {
  return array
        .filter(function(x) {
          if (!Semver.parse(x, true)) {
            Logger.logger.warn( {ver: x}, 'ignoring bad version @{ver}' )
            return false
          }
          return true
        })
        .sort(Semver.compareLoose)
        .map(String)
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/

Statements: 4.44% (6 / 135)      Branches: 2.33% (2 / 86)      Functions: 0% (0 / 15)      Lines: 4.88% (6 / 123)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/JSONStream/
File Statements Branches Functions Lines
index.js 4.44% (6 / 135) 2.33% (2 / 86) 0% (0 / 15) 4.88% (6 / 123)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/index.js

Statements: 4.44% (6 / 135)      Branches: 2.33% (2 / 86)      Functions: 0% (0 / 15)      Lines: 4.88% (6 / 123)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203    1                       1                                                                                                                                                                                                       1                       1                                                                     1                                                                   1              
//#! /usr/bin/env node
 
var Parser = require('jsonparse')
  , through = require('through')
 
/*
 
  the value of this.stack that creationix's jsonparse has is weird.
 
  it makes this code ugly, but his problem is way harder that mine,
  so i'll forgive him.
 
*/
 
exports.parse = function (path, map) {
 
  var parser = new Parser()
  var stream = through(function (chunk) {
    if('string' === typeof chunk)
      chunk = new Buffer(chunk)
    parser.write(chunk)
  },
  function (data) {
    if(data)
      stream.write(data)
    stream.queue(null)
  })
 
  if('string' === typeof path)
    path = path.split('.').map(function (e) {
      if (e === '*')
        return true
      else if (e === '') // '..'.split('.') returns an empty string
        return {recurse: true}
      else
        return e
    })
 
 
  var count = 0, _key
  if(!path || !path.length)
    path = null
 
  parser.onValue = function (value) {
    if (!this.root)
      stream.root = value
 
    if(! path) return
 
    var i = 0 // iterates on path
    var j  = 0 // iterates on stack
    while (i < path.length) {
      var key = path[i]
      var c
      j++
 
      if (key && !key.recurse) {
        c = (j === this.stack.length) ? this : this.stack[j]
        if (!c) return
        if (! check(key, c.key)) return
        i++
      } else {
        i++
        var nextKey = path[i]
        if (! nextKey) return
        while (true) {
          c = (j === this.stack.length) ? this : this.stack[j]
          if (!c) return
          if (check(nextKey, c.key)) {
            i++;
            this.stack[j].value = null
            break
          }
          j++
        }
      }
 
    }
    if (j !== this.stack.length) return
 
    count ++
    var actualPath = this.stack.slice(1).map(function(element) { return element.key }).concat([this.key])
    var data = this.value[this.key]
    if(null != data)
      if(null != (data = map ? map(data, actualPath) : data))
        stream.queue(data)
    delete this.value[this.key]
    for(var k in this.stack)
      this.stack[k].value = null
  }
  parser._onToken = parser.onToken;
 
  parser.onToken = function (token, value) {
    parser._onToken(token, value);
    if (this.stack.length === 0) {
      if (stream.root) {
        if(!path)
          stream.queue(stream.root)
        count = 0;
        stream.root = null;
      }
    }
  }
 
  parser.onError = function (err) {
    if(err.message.indexOf("at position") > -1)
      err.message = "Invalid JSON (" + err.message + ")";
    stream.emit('error', err)
  }
 
 
  return stream
}
 
function check (x, y) {
  if ('string' === typeof x)
    return y == x
  else if (x && 'function' === typeof x.exec)
    return x.exec(y)
  else if ('boolean' === typeof x)
    return x
  else if ('function' === typeof x)
    return x(y)
  return false
}
 
exports.stringify = function (op, sep, cl, indent) {
  indent = indent || 0
  if (op === false){
    op = ''
    sep = '\n'
    cl = ''
  } else if (op == null) {
 
    op = '[\n'
    sep = '\n,\n'
    cl = '\n]\n'
 
  }
 
  //else, what ever you like
 
  var stream
    , first = true
    , anyData = false
  stream = through(function (data) {
    anyData = true
    var json = JSON.stringify(data, null, indent)
    if(first) { first = false ; stream.queue(op + json)}
    else stream.queue(sep + json)
  },
  function (data) {
    if(!anyData)
      stream.queue(op)
    stream.queue(cl)
    stream.queue(null)
  })
 
  return stream
}
 
exports.stringifyObject = function (op, sep, cl, indent) {
  indent = indent || 0
  if (op === false){
    op = ''
    sep = '\n'
    cl = ''
  } else if (op == null) {
 
    op = '{\n'
    sep = '\n,\n'
    cl = '\n}\n'
 
  }
 
  //else, what ever you like
 
  var first = true
    , anyData = false
  stream = through(function (data) {
    anyData = true
    var json = JSON.stringify(data[0]) + ':' + JSON.stringify(data[1], null, indent)
    if(first) { first = false ; this.queue(op + json)}
    else this.queue(sep + json)
  },
  function (data) {
    if(!anyData) this.queue(op)
    this.queue(cl)
 
    this.queue(null)
  })
 
  return stream
}
 
Iif(!module.parent && process.title !== 'browser') {
  process.stdin
    .pipe(exports.parse(process.argv[2]))
    .pipe(exports.stringify('[', ',\n', ']\n', 2))
    .pipe(process.stdout)
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/jsonparse/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/jsonparse/

Statements: 13.46% (56 / 416)      Branches: 0% (0 / 283)      Functions: 0% (0 / 12)      Lines: 16.67% (56 / 336)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/jsonparse/
File Statements Branches Functions Lines
jsonparse.js 13.46% (56 / 416) 0% (0 / 283) 0% (0 / 12) 16.67% (56 / 336)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js

Statements: 13.46% (56 / 416)      Branches: 0% (0 / 283)      Functions: 0% (0 / 12)      Lines: 16.67% (56 / 336)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429    1   1 1 1 1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1 1   1 1     1                   1                                                   1 1     1 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1       1     1     1                 1       1     1                                                                                                                                           1   1    
/*global Buffer*/
// Named constants with unique integer values
var C = {};
// Tokens
var LEFT_BRACE    = C.LEFT_BRACE    = 0x1;
var RIGHT_BRACE   = C.RIGHT_BRACE   = 0x2;
var LEFT_BRACKET  = C.LEFT_BRACKET  = 0x3;
var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4;
var COLON         = C.COLON         = 0x5;
var COMMA         = C.COMMA         = 0x6;
var TRUE          = C.TRUE          = 0x7;
var FALSE         = C.FALSE         = 0x8;
var NULL          = C.NULL          = 0x9;
var STRING        = C.STRING        = 0xa;
var NUMBER        = C.NUMBER        = 0xb;
// Tokenizer States
var START   = C.START   = 0x11;
var TRUE1   = C.TRUE1   = 0x21;
var TRUE2   = C.TRUE2   = 0x22;
var TRUE3   = C.TRUE3   = 0x23;
var FALSE1  = C.FALSE1  = 0x31;
var FALSE2  = C.FALSE2  = 0x32;
var FALSE3  = C.FALSE3  = 0x33;
var FALSE4  = C.FALSE4  = 0x34;
var NULL1   = C.NULL1   = 0x41;
var NULL2   = C.NULL2   = 0x42;
var NULL3   = C.NULL3   = 0x43;
var NUMBER1 = C.NUMBER1 = 0x51;
var NUMBER2 = C.NUMBER2 = 0x52;
var NUMBER3 = C.NUMBER3 = 0x53;
var NUMBER4 = C.NUMBER4 = 0x54;
var NUMBER5 = C.NUMBER5 = 0x55;
var NUMBER6 = C.NUMBER6 = 0x56;
var NUMBER7 = C.NUMBER7 = 0x57;
var NUMBER8 = C.NUMBER8 = 0x58;
var STRING1 = C.STRING1 = 0x61;
var STRING2 = C.STRING2 = 0x62;
var STRING3 = C.STRING3 = 0x63;
var STRING4 = C.STRING4 = 0x64;
var STRING5 = C.STRING5 = 0x65;
var STRING6 = C.STRING6 = 0x66;
// Parser States
var VALUE   = C.VALUE   = 0x71;
var KEY     = C.KEY     = 0x72;
// Parser Modes
var OBJECT  = C.OBJECT  = 0x81;
var ARRAY   = C.ARRAY   = 0x82;
 
// Slow code to string converter (only used when throwing syntax errors)
function toknam(code) {
  var keys = Object.keys(C);
  for (var i = 0, l = keys.length; i < l; i++) {
    var key = keys[i];
    if (C[key] === code) { return key; }
  }
  return code && ("0x" + code.toString(16));
}
 
 
function Parser() {
  this.tState = START;
  this.value = undefined;
 
  this.string = undefined; // string data
  this.unicode = undefined; // unicode escapes
 
  // For number parsing
  this.negative = undefined;
  this.magnatude = undefined;
  this.position = undefined;
  this.exponent = undefined;
  this.negativeExponent = undefined;
  this.numberLength = 0;
  
  this.key = undefined;
  this.mode = undefined;
  this.stack = [];
  this.state = VALUE;
  this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary
  this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read
  this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached
 
  // Stream offset
  this.offset = -1;
}
var proto = Parser.prototype;
proto.charError = function (buffer, i) {
  this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + toknam(this.tState)));
};
proto.onError = function (err) { throw err; };
proto.write = function (buffer) {
  if (typeof buffer === "string") buffer = new Buffer(buffer);
  //process.stdout.write("Input: ");
  //console.dir(buffer.toString());
  var n;
  for (var i = 0, l = buffer.length; i < l; i++) {
    if (this.tState === START){
      n = buffer[i];
      this.offset++;
      if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // {
      }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // }
      }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [
      }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ]
      }else if(n === 0x3a){ this.onToken(COLON, ":");  // :
      }else if(n === 0x2c){ this.onToken(COMMA, ","); // ,
      }else if(n === 0x74){ this.tState = TRUE1;  // t
      }else if(n === 0x66){ this.tState = FALSE1;  // f
      }else if(n === 0x6e){ this.tState = NULL1; // n
      }else if(n === 0x22){ this.string = ""; this.tState = STRING1; // "
      }else if(n === 0x2d){ this.negative = true; this.tState = NUMBER1; // -
      }else if(n === 0x30){ this.magnatude = 0; this.tState = NUMBER2; // 0
      }else{
        if (n > 0x30 && n < 0x40) { // 1-9
          this.magnatude = n - 0x30; this.tState = NUMBER3;
        } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) {
          // whitespace
        } else { this.charError(buffer, i); }
      }
    }else if (this.tState === STRING1){ // After open quote
      n = buffer[i]; // get current byte from buffer
      // check for carry over of a multi byte char split between data chunks
      // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration
      if (this.bytes_remaining > 0) {
        for (var j = 0; j < this.bytes_remaining; j++) {
          this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j];
        }
        this.string += this.temp_buffs[this.bytes_in_sequence].toString();
        this.bytes_in_sequence = this.bytes_remaining = 0;
        i = i + j - 1;
      } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time
        if (n <= 193) {
          this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + toknam(this.tState)));
          return
        }
        if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;
        if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;
        if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;
        if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split
          for (var k = 0; k <= (buffer.length - 1 - i); k++) {
            this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk
          }
          this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length;
          i = buffer.length - 1;
        } else {
          this.string += buffer.slice(i, (i + this.bytes_in_sequence)).toString();
          i = i + this.bytes_in_sequence - 1;
        }
      } else if (n === 0x22) { this.tState = START; this.onToken(STRING, this.string); this.offset += Buffer.byteLength(this.string, 'utf8') + 1; this.string = undefined; }
      else if (n === 0x5c) { this.tState = STRING2; }
      else if (n >= 0x20) { this.string += String.fromCharCode(n); }
      else { this.charError(buffer, i); }
    }else if (this.tState === STRING2){ // After backslash
      n = buffer[i];
      if(n === 0x22){ this.string += "\""; this.tState = STRING1;
      }else if(n === 0x5c){ this.string += "\\"; this.tState = STRING1; 
      }else if(n === 0x2f){ this.string += "\/"; this.tState = STRING1; 
      }else if(n === 0x62){ this.string += "\b"; this.tState = STRING1; 
      }else if(n === 0x66){ this.string += "\f"; this.tState = STRING1; 
      }else if(n === 0x6e){ this.string += "\n"; this.tState = STRING1; 
      }else if(n === 0x72){ this.string += "\r"; this.tState = STRING1; 
      }else if(n === 0x74){ this.string += "\t"; this.tState = STRING1; 
      }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3;
      }else{ 
        this.charError(buffer, i); 
      }
    }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes
      n = buffer[i];
      // 0-9 A-F a-f
      if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) {
        this.unicode += String.fromCharCode(n);
        if (this.tState++ === STRING6) {
          this.string += String.fromCharCode(parseInt(this.unicode, 16));
          this.unicode = undefined;
          this.tState = STRING1; 
        }
      } else {
        this.charError(buffer, i);
      }
    }else if (this.tState === NUMBER1){ // after minus
      n = buffer[i];
      this.numberLength++;
      if (n === 0x30) { this.magnatude = 0; this.tState = NUMBER2; }
      else if (n > 0x30 && n < 0x40) { this.magnatude = n - 0x30; this.tState = NUMBER3; }
      else { this.charError(buffer, i); }
    }else if (this.tState === NUMBER2){ // * After initial zero
      n = buffer[i];
      this.numberLength++;
      if(n === 0x2e){ // .
        this.position = 0.1; this.tState = NUMBER4;
      }else if(n === 0x65 ||  n === 0x45){ // e/E
        this.exponent = 0; this.tState = NUMBER6;
      }else{
        this.tState = START;
        this.onToken(NUMBER, 0);
        this.offset += this.numberLength - 1;
        this.numberLength = 0;
        this.magnatude = undefined;
        this.negative = undefined;
        i--;
      }
    }else if (this.tState === NUMBER3){ // * After digit (before period)
      n = buffer[i];
      this.numberLength++;
      if(n === 0x2e){ // .
        this.position = 0.1; this.tState = NUMBER4;
      }else if(n === 0x65 || n === 0x45){ // e/E
        this.exponent = 0; this.tState = NUMBER6;
      }else{
        if (n >= 0x30 && n < 0x40) { this.magnatude = this.magnatude * 10 + n - 0x30; }
        else {
          this.tState = START; 
          if (this.negative) {
            this.magnatude = -this.magnatude;
            this.negative = undefined;
          }
          this.onToken(NUMBER, this.magnatude); 
          this.offset += this.numberLength - 1;
          this.numberLength = 0;
          this.magnatude = undefined;
          i--;
        }
      }
    }else if (this.tState === NUMBER4){ // After period
      n = buffer[i];
      this.numberLength++;
      if (n >= 0x30 && n < 0x40) { // 0-9
        this.magnatude += this.position * (n - 0x30);
        this.position /= 10;
        this.tState = NUMBER5; 
      } else { this.charError(buffer, i); }
    }else if (this.tState === NUMBER5){ // * After digit (after period)
      n = buffer[i];
      this.numberLength++;
      if (n >= 0x30 && n < 0x40) { // 0-9
        this.magnatude += this.position * (n - 0x30);
        this.position /= 10;
      }
      else if (n === 0x65 || n === 0x45) { this.exponent = 0; this.tState = NUMBER6; } // E/e
      else {
        this.tState = START; 
        if (this.negative) {
          this.magnatude = -this.magnatude;
          this.negative = undefined;
        }
        this.onToken(NUMBER, this.negative ? -this.magnatude : this.magnatude); 
        this.offset += this.numberLength - 1;
        this.numberLength = 0;
        this.magnatude = undefined;
        this.position = undefined;
        i--; 
      }
    }else if (this.tState === NUMBER6){ // After E
      n = buffer[i];
      this.numberLength++;
      if (n === 0x2b || n === 0x2d) { // +/-
        if (n === 0x2d) { this.negativeExponent = true; }
        this.tState = NUMBER7;
      }
      else if (n >= 0x30 && n < 0x40) {
        this.exponent = this.exponent * 10 + (n - 0x30);
        this.tState = NUMBER8;
      }
      else { this.charError(buffer, i); }  
    }else if (this.tState === NUMBER7){ // After +/-
      n = buffer[i];
      this.numberLength++;
      if (n >= 0x30 && n < 0x40) { // 0-9
        this.exponent = this.exponent * 10 + (n - 0x30);
        this.tState = NUMBER8;
      }
      else { this.charError(buffer, i); }  
    }else if (this.tState === NUMBER8){ // * After digit (after +/-)
      n = buffer[i];
      this.numberLength++;
      if (n >= 0x30 && n < 0x40) { // 0-9
        this.exponent = this.exponent * 10 + (n - 0x30);
      }
      else {
        if (this.negativeExponent) {
          this.exponent = -this.exponent;
          this.negativeExponent = undefined;
        }
        this.magnatude *= Math.pow(10, this.exponent);
        this.exponent = undefined;
        if (this.negative) { 
          this.magnatude = -this.magnatude;
          this.negative = undefined;
        }
        this.tState = START;
        this.onToken(NUMBER, this.magnatude);
        this.offset += this.numberLength - 1;
        this.numberLength = 0;
        this.magnatude = undefined;
        i--; 
      } 
    }else if (this.tState === TRUE1){ // r
      if (buffer[i] === 0x72) { this.tState = TRUE2; }
      else { this.charError(buffer, i); }
    }else if (this.tState === TRUE2){ // u
      if (buffer[i] === 0x75) { this.tState = TRUE3; }
      else { this.charError(buffer, i); }
    }else if (this.tState === TRUE3){ // e
      if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; }
      else { this.charError(buffer, i); }
    }else if (this.tState === FALSE1){ // a
      if (buffer[i] === 0x61) { this.tState = FALSE2; }
      else { this.charError(buffer, i); }
    }else if (this.tState === FALSE2){ // l
      if (buffer[i] === 0x6c) { this.tState = FALSE3; }
      else { this.charError(buffer, i); }
    }else if (this.tState === FALSE3){ // s
      if (buffer[i] === 0x73) { this.tState = FALSE4; }
      else { this.charError(buffer, i); }
    }else if (this.tState === FALSE4){ // e
      if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; }
      else { this.charError(buffer, i); }
    }else if (this.tState === NULL1){ // u
      if (buffer[i] === 0x75) { this.tState = NULL2; }
      else { this.charError(buffer, i); }
    }else if (this.tState === NULL2){ // l
      if (buffer[i] === 0x6c) { this.tState = NULL3; }
      else { this.charError(buffer, i); }
    }else if (this.tState === NULL3){ // l
      if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; }
      else { this.charError(buffer, i); }
    }
  }
};
proto.onToken = function (token, value) {
  // Override this to get events
};
 
proto.parseError = function (token, value) {
  this.onError(new Error("Unexpected " + toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + toknam(this.state)));
};
proto.push = function () {
  this.stack.push({value: this.value, key: this.key, mode: this.mode});
};
proto.pop = function () {
  var value = this.value;
  var parent = this.stack.pop();
  this.value = parent.value;
  this.key = parent.key;
  this.mode = parent.mode;
  this.emit(value);
  if (!this.mode) { this.state = VALUE; }
};
proto.emit = function (value) {
  if (this.mode) { this.state = COMMA; }
  this.onValue(value);
};
proto.onValue = function (value) {
  // Override me
};  
proto.onToken = function (token, value) {
  //console.log("OnToken: state=%s token=%s %s", toknam(this.state), toknam(token), value?JSON.stringify(value):"");
  if(this.state === VALUE){
    if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){
      if (this.value) {
        this.value[this.key] = value;
      }
      this.emit(value);  
    }else if(token === LEFT_BRACE){
      this.push();
      if (this.value) {
        this.value = this.value[this.key] = {};
      } else {
        this.value = {};
      }
      this.key = undefined;
      this.state = KEY;
      this.mode = OBJECT;
    }else if(token === LEFT_BRACKET){
      this.push();
      if (this.value) {
        this.value = this.value[this.key] = [];
      } else {
        this.value = [];
      }
      this.key = 0;
      this.mode = ARRAY;
      this.state = VALUE;
    }else if(token === RIGHT_BRACE){
      if (this.mode === OBJECT) {
        this.pop();
      } else {
        this.parseError(token, value);
      }
    }else if(token === RIGHT_BRACKET){
      if (this.mode === ARRAY) {
        this.pop();
      } else {
        this.parseError(token, value);
      }
    }else{
      this.parseError(token, value);
    }
  }else if(this.state === KEY){
    if (token === STRING) {
      this.key = value;
      this.state = COLON;
    } else if (token === RIGHT_BRACE) {
      this.pop();
    } else {
      this.parseError(token, value);
    }
  }else if(this.state === COLON){
    if (token === COLON) { this.state = VALUE; }
    else { this.parseError(token, value); }
  }else if(this.state === COMMA){
    if (token === COMMA) { 
      if (this.mode === ARRAY) { this.key++; this.state = VALUE; }
      else if (this.mode === OBJECT) { this.state = KEY; }
 
    } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) {
      this.pop();
    } else {
      this.parseError(token, value);
    }
  }else{
    this.parseError(token, value);
  }
};
 
Parser.C = C;
 
module.exports = Parser;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/through/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/through/

Statements: 8.45% (6 / 71)      Branches: 0% (0 / 34)      Functions: 0% (0 / 13)      Lines: 9.52% (6 / 63)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/through/
File Statements Branches Functions Lines
index.js 8.45% (6 / 71) 0% (0 / 34) 0% (0 / 13) 9.52% (6 / 63)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/through/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/JSONStream/node_modules/through/index.js

Statements: 8.45% (6 / 71)      Branches: 0% (0 / 34)      Functions: 0% (0 / 13)      Lines: 9.52% (6 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 1101             1 1       1                                 1                                                                 1                                                                                              
var Stream = require('stream')
 
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
 
exports = module.exports = through
through.through = through
 
//create a readable writable stream.
 
function through (write, end, opts) {
  write = write || function (data) { this.queue(data) }
  end = end || function () { this.queue(null) }
 
  var ended = false, destroyed = false, buffer = [], _ended = false
  var stream = new Stream()
  stream.readable = stream.writable = true
  stream.paused = false
 
//  stream.autoPause   = !(opts && opts.autoPause   === false)
  stream.autoDestroy = !(opts && opts.autoDestroy === false)
 
  stream.write = function (data) {
    write.call(this, data)
    return !stream.paused
  }
 
  function drain() {
    while(buffer.length && !stream.paused) {
      var data = buffer.shift()
      if(null === data)
        return stream.emit('end')
      else
        stream.emit('data', data)
    }
  }
 
  stream.queue = stream.push = function (data) {
//    console.error(ended)
    if(_ended) return stream
    if(data === null) _ended = true
    buffer.push(data)
    drain()
    return stream
  }
 
  //this will be registered as the first 'end' listener
  //must call destroy next tick, to make sure we're after any
  //stream piped from here.
  //this is only a problem if end is not emitted synchronously.
  //a nicer way to do this is to make sure this is the last listener for 'end'
 
  stream.on('end', function () {
    stream.readable = false
    if(!stream.writable && stream.autoDestroy)
      process.nextTick(function () {
        stream.destroy()
      })
  })
 
  function _end () {
    stream.writable = false
    end.call(stream)
    if(!stream.readable && stream.autoDestroy)
      stream.destroy()
  }
 
  stream.end = function (data) {
    if(ended) return
    ended = true
    if(arguments.length) stream.write(data)
    _end() // will emit or queue
    return stream
  }
 
  stream.destroy = function () {
    if(destroyed) return
    destroyed = true
    ended = true
    buffer.length = 0
    stream.writable = stream.readable = false
    stream.emit('close')
    return stream
  }
 
  stream.pause = function () {
    if(stream.paused) return
    stream.paused = true
    return stream
  }
 
  stream.resume = function () {
    if(stream.paused) {
      stream.paused = false
      stream.emit('resume')
    }
    drain()
    //may have become paused again,
    //as drain emits 'data'.
    if(!stream.paused)
      stream.emit('drain')
    return stream
  }
  return stream
}
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/async/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/async/lib/

Statements: 15.59% (97 / 622)      Branches: 3.42% (9 / 263)      Functions: 1.97% (4 / 203)      Lines: 15.75% (97 / 616)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/async/lib/
File Statements Branches Functions Lines
async.js 15.59% (97 / 622) 3.42% (9 / 263) 1.97% (4 / 203) 15.75% (97 / 616)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/async/lib/async.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/async/lib/async.js

Statements: 15.59% (97 / 622)      Branches: 3.42% (9 / 263)      Functions: 1.97% (4 / 203)      Lines: 15.75% (97 / 616)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125                  1   1     1   1 1 1     1         1                     1   1       1           1                     1                   1                               1                               1 1 1                   1                 1                         1   1                                                 1   1       1   1                                                                                 1 6         1           1 6             1                                           1 1 1       1           1                     1   1   1             1   1                                       1 1   1 1   1                                       1 1   1                             1 1   1                           1   1                           1   1                                                   1                                                                                                                                                                   1                                                             1                                                                 1                                                               1       1       1                                                               1                               1                 1                     1 1   1                           1                             1                           1                             1       1                                                                                                                                                                                                       1   1       1                           1                                                                                         1                                                                                                                                       1 2                                     1 1         1                                                                     1           1               1               1                                     1       1                                   1 1   1 1                         1 1                              
/*!
 * async
 * https://github.com/caolan/async
 *
 * Copyright 2010-2014 Caolan McMahon
 * Released under the MIT license
 */
/*jshint onevar: false, indent:4 */
/*global setImmediate: false, setTimeout: false, console: false */
(function () {
 
    var async = {};
 
    // global on the server, window in the browser
    var root, previous_async;
 
    root = this;
    Eif (root != null) {
      previous_async = root.async;
    }
 
    async.noConflict = function () {
        root.async = previous_async;
        return async;
    };
 
    function only_once(fn) {
        var called = false;
        return function() {
            if (called) throw new Error("Callback was already called.");
            called = true;
            fn.apply(root, arguments);
        }
    }
 
    //// cross-browser compatiblity functions ////
 
    var _toString = Object.prototype.toString;
 
    var _isArray = Array.isArray || function (obj) {
        return _toString.call(obj) === '[object Array]';
    };
 
    var _each = function (arr, iterator) {
        for (var i = 0; i < arr.length; i += 1) {
            iterator(arr[i], i, arr);
        }
    };
 
    var _map = function (arr, iterator) {
        if (arr.map) {
            return arr.map(iterator);
        }
        var results = [];
        _each(arr, function (x, i, a) {
            results.push(iterator(x, i, a));
        });
        return results;
    };
 
    var _reduce = function (arr, iterator, memo) {
        if (arr.reduce) {
            return arr.reduce(iterator, memo);
        }
        _each(arr, function (x, i, a) {
            memo = iterator(memo, x, i, a);
        });
        return memo;
    };
 
    var _keys = function (obj) {
        if (Object.keys) {
            return Object.keys(obj);
        }
        var keys = [];
        for (var k in obj) {
            if (obj.hasOwnProperty(k)) {
                keys.push(k);
            }
        }
        return keys;
    };
 
    //// exported async module functions ////
 
    //// nextTick implementation with browser-compatible fallback ////
    Iif (typeof process === 'undefined' || !(process.nextTick)) {
        if (typeof setImmediate === 'function') {
            async.nextTick = function (fn) {
                // not a direct alias for IE10 compatibility
                setImmediate(fn);
            };
            async.setImmediate = async.nextTick;
        }
        else {
            async.nextTick = function (fn) {
                setTimeout(fn, 0);
            };
            async.setImmediate = async.nextTick;
        }
    }
    else {
        async.nextTick = process.nextTick;
        Eif (typeof setImmediate !== 'undefined') {
            async.setImmediate = function (fn) {
              // not a direct alias for IE10 compatibility
              setImmediate(fn);
            };
        }
        else {
            async.setImmediate = async.nextTick;
        }
    }
 
    async.each = function (arr, iterator, callback) {
        callback = callback || function () {};
        if (!arr.length) {
            return callback();
        }
        var completed = 0;
        _each(arr, function (x) {
            iterator(x, only_once(done) );
        });
        function done(err) {
          if (err) {
              callback(err);
              callback = function () {};
          }
          else {
              completed += 1;
              if (completed >= arr.length) {
                  callback();
              }
          }
        }
    };
    async.forEach = async.each;
 
    async.eachSeries = function (arr, iterator, callback) {
        callback = callback || function () {};
        if (!arr.length) {
            return callback();
        }
        var completed = 0;
        var iterate = function () {
            iterator(arr[completed], function (err) {
                if (err) {
                    callback(err);
                    callback = function () {};
                }
                else {
                    completed += 1;
                    if (completed >= arr.length) {
                        callback();
                    }
                    else {
                        iterate();
                    }
                }
            });
        };
        iterate();
    };
    async.forEachSeries = async.eachSeries;
 
    async.eachLimit = function (arr, limit, iterator, callback) {
        var fn = _eachLimit(limit);
        fn.apply(null, [arr, iterator, callback]);
    };
    async.forEachLimit = async.eachLimit;
 
    var _eachLimit = function (limit) {
 
        return function (arr, iterator, callback) {
            callback = callback || function () {};
            if (!arr.length || limit <= 0) {
                return callback();
            }
            var completed = 0;
            var started = 0;
            var running = 0;
 
            (function replenish () {
                if (completed >= arr.length) {
                    return callback();
                }
 
                while (running < limit && started < arr.length) {
                    started += 1;
                    running += 1;
                    iterator(arr[started - 1], function (err) {
                        if (err) {
                            callback(err);
                            callback = function () {};
                        }
                        else {
                            completed += 1;
                            running -= 1;
                            if (completed >= arr.length) {
                                callback();
                            }
                            else {
                                replenish();
                            }
                        }
                    });
                }
            })();
        };
    };
 
 
    var doParallel = function (fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return fn.apply(null, [async.each].concat(args));
        };
    };
    var doParallelLimit = function(limit, fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return fn.apply(null, [_eachLimit(limit)].concat(args));
        };
    };
    var doSeries = function (fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return fn.apply(null, [async.eachSeries].concat(args));
        };
    };
 
 
    var _asyncMap = function (eachfn, arr, iterator, callback) {
        arr = _map(arr, function (x, i) {
            return {index: i, value: x};
        });
        if (!callback) {
            eachfn(arr, function (x, callback) {
                iterator(x.value, function (err) {
                    callback(err);
                });
            });
        } else {
            var results = [];
            eachfn(arr, function (x, callback) {
                iterator(x.value, function (err, v) {
                    results[x.index] = v;
                    callback(err);
                });
            }, function (err) {
                callback(err, results);
            });
        }
    };
    async.map = doParallel(_asyncMap);
    async.mapSeries = doSeries(_asyncMap);
    async.mapLimit = function (arr, limit, iterator, callback) {
        return _mapLimit(limit)(arr, iterator, callback);
    };
 
    var _mapLimit = function(limit) {
        return doParallelLimit(limit, _asyncMap);
    };
 
    // reduce only has a series version, as doing reduce in parallel won't
    // work in many situations.
    async.reduce = function (arr, memo, iterator, callback) {
        async.eachSeries(arr, function (x, callback) {
            iterator(memo, x, function (err, v) {
                memo = v;
                callback(err);
            });
        }, function (err) {
            callback(err, memo);
        });
    };
    // inject alias
    async.inject = async.reduce;
    // foldl alias
    async.foldl = async.reduce;
 
    async.reduceRight = function (arr, memo, iterator, callback) {
        var reversed = _map(arr, function (x) {
            return x;
        }).reverse();
        async.reduce(reversed, memo, iterator, callback);
    };
    // foldr alias
    async.foldr = async.reduceRight;
 
    var _filter = function (eachfn, arr, iterator, callback) {
        var results = [];
        arr = _map(arr, function (x, i) {
            return {index: i, value: x};
        });
        eachfn(arr, function (x, callback) {
            iterator(x.value, function (v) {
                if (v) {
                    results.push(x);
                }
                callback();
            });
        }, function (err) {
            callback(_map(results.sort(function (a, b) {
                return a.index - b.index;
            }), function (x) {
                return x.value;
            }));
        });
    };
    async.filter = doParallel(_filter);
    async.filterSeries = doSeries(_filter);
    // select alias
    async.select = async.filter;
    async.selectSeries = async.filterSeries;
 
    var _reject = function (eachfn, arr, iterator, callback) {
        var results = [];
        arr = _map(arr, function (x, i) {
            return {index: i, value: x};
        });
        eachfn(arr, function (x, callback) {
            iterator(x.value, function (v) {
                if (!v) {
                    results.push(x);
                }
                callback();
            });
        }, function (err) {
            callback(_map(results.sort(function (a, b) {
                return a.index - b.index;
            }), function (x) {
                return x.value;
            }));
        });
    };
    async.reject = doParallel(_reject);
    async.rejectSeries = doSeries(_reject);
 
    var _detect = function (eachfn, arr, iterator, main_callback) {
        eachfn(arr, function (x, callback) {
            iterator(x, function (result) {
                if (result) {
                    main_callback(x);
                    main_callback = function () {};
                }
                else {
                    callback();
                }
            });
        }, function (err) {
            main_callback();
        });
    };
    async.detect = doParallel(_detect);
    async.detectSeries = doSeries(_detect);
 
    async.some = function (arr, iterator, main_callback) {
        async.each(arr, function (x, callback) {
            iterator(x, function (v) {
                if (v) {
                    main_callback(true);
                    main_callback = function () {};
                }
                callback();
            });
        }, function (err) {
            main_callback(false);
        });
    };
    // any alias
    async.any = async.some;
 
    async.every = function (arr, iterator, main_callback) {
        async.each(arr, function (x, callback) {
            iterator(x, function (v) {
                if (!v) {
                    main_callback(false);
                    main_callback = function () {};
                }
                callback();
            });
        }, function (err) {
            main_callback(true);
        });
    };
    // all alias
    async.all = async.every;
 
    async.sortBy = function (arr, iterator, callback) {
        async.map(arr, function (x, callback) {
            iterator(x, function (err, criteria) {
                if (err) {
                    callback(err);
                }
                else {
                    callback(null, {value: x, criteria: criteria});
                }
            });
        }, function (err, results) {
            if (err) {
                return callback(err);
            }
            else {
                var fn = function (left, right) {
                    var a = left.criteria, b = right.criteria;
                    return a < b ? -1 : a > b ? 1 : 0;
                };
                callback(null, _map(results.sort(fn), function (x) {
                    return x.value;
                }));
            }
        });
    };
 
    async.auto = function (tasks, callback) {
        callback = callback || function () {};
        var keys = _keys(tasks);
        var remainingTasks = keys.length
        if (!remainingTasks) {
            return callback();
        }
 
        var results = {};
 
        var listeners = [];
        var addListener = function (fn) {
            listeners.unshift(fn);
        };
        var removeListener = function (fn) {
            for (var i = 0; i < listeners.length; i += 1) {
                if (listeners[i] === fn) {
                    listeners.splice(i, 1);
                    return;
                }
            }
        };
        var taskComplete = function () {
            remainingTasks--
            _each(listeners.slice(0), function (fn) {
                fn();
            });
        };
 
        addListener(function () {
            if (!remainingTasks) {
                var theCallback = callback;
                // prevent final callback from calling itself if it errors
                callback = function () {};
 
                theCallback(null, results);
            }
        });
 
        _each(keys, function (k) {
            var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
            var taskCallback = function (err) {
                var args = Array.prototype.slice.call(arguments, 1);
                if (args.length <= 1) {
                    args = args[0];
                }
                if (err) {
                    var safeResults = {};
                    _each(_keys(results), function(rkey) {
                        safeResults[rkey] = results[rkey];
                    });
                    safeResults[k] = args;
                    callback(err, safeResults);
                    // stop subsequent errors hitting callback multiple times
                    callback = function () {};
                }
                else {
                    results[k] = args;
                    async.setImmediate(taskComplete);
                }
            };
            var requires = task.slice(0, Math.abs(task.length - 1)) || [];
            var ready = function () {
                return _reduce(requires, function (a, x) {
                    return (a && results.hasOwnProperty(x));
                }, true) && !results.hasOwnProperty(k);
            };
            if (ready()) {
                task[task.length - 1](taskCallback, results);
            }
            else {
                var listener = function () {
                    if (ready()) {
                        removeListener(listener);
                        task[task.length - 1](taskCallback, results);
                    }
                };
                addListener(listener);
            }
        });
    };
 
    async.retry = function(times, task, callback) {
        var DEFAULT_TIMES = 5;
        var attempts = [];
        // Use defaults if times not passed
        if (typeof times === 'function') {
            callback = task;
            task = times;
            times = DEFAULT_TIMES;
        }
        // Make sure times is a number
        times = parseInt(times, 10) || DEFAULT_TIMES;
        var wrappedTask = function(wrappedCallback, wrappedResults) {
            var retryAttempt = function(task, finalAttempt) {
                return function(seriesCallback) {
                    task(function(err, result){
                        seriesCallback(!err || finalAttempt, {err: err, result: result});
                    }, wrappedResults);
                };
            };
            while (times) {
                attempts.push(retryAttempt(task, !(times-=1)));
            }
            async.series(attempts, function(done, data){
                data = data[data.length - 1];
                (wrappedCallback || callback)(data.err, data.result);
            });
        }
        // If a callback is passed, run this as a controll flow
        return callback ? wrappedTask() : wrappedTask
    };
 
    async.waterfall = function (tasks, callback) {
        callback = callback || function () {};
        if (!_isArray(tasks)) {
          var err = new Error('First argument to waterfall must be an array of functions');
          return callback(err);
        }
        if (!tasks.length) {
            return callback();
        }
        var wrapIterator = function (iterator) {
            return function (err) {
                if (err) {
                    callback.apply(null, arguments);
                    callback = function () {};
                }
                else {
                    var args = Array.prototype.slice.call(arguments, 1);
                    var next = iterator.next();
                    if (next) {
                        args.push(wrapIterator(next));
                    }
                    else {
                        args.push(callback);
                    }
                    async.setImmediate(function () {
                        iterator.apply(null, args);
                    });
                }
            };
        };
        wrapIterator(async.iterator(tasks))();
    };
 
    var _parallel = function(eachfn, tasks, callback) {
        callback = callback || function () {};
        if (_isArray(tasks)) {
            eachfn.map(tasks, function (fn, callback) {
                if (fn) {
                    fn(function (err) {
                        var args = Array.prototype.slice.call(arguments, 1);
                        if (args.length <= 1) {
                            args = args[0];
                        }
                        callback.call(null, err, args);
                    });
                }
            }, callback);
        }
        else {
            var results = {};
            eachfn.each(_keys(tasks), function (k, callback) {
                tasks[k](function (err) {
                    var args = Array.prototype.slice.call(arguments, 1);
                    if (args.length <= 1) {
                        args = args[0];
                    }
                    results[k] = args;
                    callback(err);
                });
            }, function (err) {
                callback(err, results);
            });
        }
    };
 
    async.parallel = function (tasks, callback) {
        _parallel({ map: async.map, each: async.each }, tasks, callback);
    };
 
    async.parallelLimit = function(tasks, limit, callback) {
        _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
    };
 
    async.series = function (tasks, callback) {
        callback = callback || function () {};
        if (_isArray(tasks)) {
            async.mapSeries(tasks, function (fn, callback) {
                if (fn) {
                    fn(function (err) {
                        var args = Array.prototype.slice.call(arguments, 1);
                        if (args.length <= 1) {
                            args = args[0];
                        }
                        callback.call(null, err, args);
                    });
                }
            }, callback);
        }
        else {
            var results = {};
            async.eachSeries(_keys(tasks), function (k, callback) {
                tasks[k](function (err) {
                    var args = Array.prototype.slice.call(arguments, 1);
                    if (args.length <= 1) {
                        args = args[0];
                    }
                    results[k] = args;
                    callback(err);
                });
            }, function (err) {
                callback(err, results);
            });
        }
    };
 
    async.iterator = function (tasks) {
        var makeCallback = function (index) {
            var fn = function () {
                if (tasks.length) {
                    tasks[index].apply(null, arguments);
                }
                return fn.next();
            };
            fn.next = function () {
                return (index < tasks.length - 1) ? makeCallback(index + 1): null;
            };
            return fn;
        };
        return makeCallback(0);
    };
 
    async.apply = function (fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function () {
            return fn.apply(
                null, args.concat(Array.prototype.slice.call(arguments))
            );
        };
    };
 
    var _concat = function (eachfn, arr, fn, callback) {
        var r = [];
        eachfn(arr, function (x, cb) {
            fn(x, function (err, y) {
                r = r.concat(y || []);
                cb(err);
            });
        }, function (err) {
            callback(err, r);
        });
    };
    async.concat = doParallel(_concat);
    async.concatSeries = doSeries(_concat);
 
    async.whilst = function (test, iterator, callback) {
        if (test()) {
            iterator(function (err) {
                if (err) {
                    return callback(err);
                }
                async.whilst(test, iterator, callback);
            });
        }
        else {
            callback();
        }
    };
 
    async.doWhilst = function (iterator, test, callback) {
        iterator(function (err) {
            if (err) {
                return callback(err);
            }
            var args = Array.prototype.slice.call(arguments, 1);
            if (test.apply(null, args)) {
                async.doWhilst(iterator, test, callback);
            }
            else {
                callback();
            }
        });
    };
 
    async.until = function (test, iterator, callback) {
        if (!test()) {
            iterator(function (err) {
                if (err) {
                    return callback(err);
                }
                async.until(test, iterator, callback);
            });
        }
        else {
            callback();
        }
    };
 
    async.doUntil = function (iterator, test, callback) {
        iterator(function (err) {
            if (err) {
                return callback(err);
            }
            var args = Array.prototype.slice.call(arguments, 1);
            if (!test.apply(null, args)) {
                async.doUntil(iterator, test, callback);
            }
            else {
                callback();
            }
        });
    };
 
    async.queue = function (worker, concurrency) {
        if (concurrency === undefined) {
            concurrency = 1;
        }
        function _insert(q, data, pos, callback) {
          if (!q.started){
            q.started = true;
          }
          if (!_isArray(data)) {
              data = [data];
          }
          if(data.length == 0) {
             // call drain immediately if there are no tasks
             return async.setImmediate(function() {
                 if (q.drain) {
                     q.drain();
                 }
             });
          }
          _each(data, function(task) {
              var item = {
                  data: task,
                  callback: typeof callback === 'function' ? callback : null
              };
 
              if (pos) {
                q.tasks.unshift(item);
              } else {
                q.tasks.push(item);
              }
 
              if (q.saturated && q.tasks.length === q.concurrency) {
                  q.saturated();
              }
              async.setImmediate(q.process);
          });
        }
 
        var workers = 0;
        var q = {
            tasks: [],
            concurrency: concurrency,
            saturated: null,
            empty: null,
            drain: null,
            started: false,
            paused: false,
            push: function (data, callback) {
              _insert(q, data, false, callback);
            },
            kill: function () {
              q.drain = null;
              q.tasks = [];
            },
            unshift: function (data, callback) {
              _insert(q, data, true, callback);
            },
            process: function () {
                if (!q.paused && workers < q.concurrency && q.tasks.length) {
                    var task = q.tasks.shift();
                    if (q.empty && q.tasks.length === 0) {
                        q.empty();
                    }
                    workers += 1;
                    var next = function () {
                        workers -= 1;
                        if (task.callback) {
                            task.callback.apply(task, arguments);
                        }
                        if (q.drain && q.tasks.length + workers === 0) {
                            q.drain();
                        }
                        q.process();
                    };
                    var cb = only_once(next);
                    worker(task.data, cb);
                }
            },
            length: function () {
                return q.tasks.length;
            },
            running: function () {
                return workers;
            },
            idle: function() {
                return q.tasks.length + workers === 0;
            },
            pause: function () {
                if (q.paused === true) { return; }
                q.paused = true;
            },
            resume: function () {
                if (q.paused === false) { return; }
                q.paused = false;
                // Need to call q.process once per concurrent
                // worker to preserve full concurrency after pause
                for (var w = 1; w <= q.concurrency; w++) {
                    async.setImmediate(q.process);
                }
            }
        };
        return q;
    };
 
    async.priorityQueue = function (worker, concurrency) {
 
        function _compareTasks(a, b){
          return a.priority - b.priority;
        };
 
        function _binarySearch(sequence, item, compare) {
          var beg = -1,
              end = sequence.length - 1;
          while (beg < end) {
            var mid = beg + ((end - beg + 1) >>> 1);
            if (compare(item, sequence[mid]) >= 0) {
              beg = mid;
            } else {
              end = mid - 1;
            }
          }
          return beg;
        }
 
        function _insert(q, data, priority, callback) {
          if (!q.started){
            q.started = true;
          }
          if (!_isArray(data)) {
              data = [data];
          }
          if(data.length == 0) {
             // call drain immediately if there are no tasks
             return async.setImmediate(function() {
                 if (q.drain) {
                     q.drain();
                 }
             });
          }
          _each(data, function(task) {
              var item = {
                  data: task,
                  priority: priority,
                  callback: typeof callback === 'function' ? callback : null
              };
 
              q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
 
              if (q.saturated && q.tasks.length === q.concurrency) {
                  q.saturated();
              }
              async.setImmediate(q.process);
          });
        }
 
        // Start with a normal queue
        var q = async.queue(worker, concurrency);
 
        // Override push to accept second parameter representing priority
        q.push = function (data, priority, callback) {
          _insert(q, data, priority, callback);
        };
 
        // Remove unshift function
        delete q.unshift;
 
        return q;
    };
 
    async.cargo = function (worker, payload) {
        var working     = false,
            tasks       = [];
 
        var cargo = {
            tasks: tasks,
            payload: payload,
            saturated: null,
            empty: null,
            drain: null,
            drained: true,
            push: function (data, callback) {
                if (!_isArray(data)) {
                    data = [data];
                }
                _each(data, function(task) {
                    tasks.push({
                        data: task,
                        callback: typeof callback === 'function' ? callback : null
                    });
                    cargo.drained = false;
                    if (cargo.saturated && tasks.length === payload) {
                        cargo.saturated();
                    }
                });
                async.setImmediate(cargo.process);
            },
            process: function process() {
                if (working) return;
                if (tasks.length === 0) {
                    if(cargo.drain && !cargo.drained) cargo.drain();
                    cargo.drained = true;
                    return;
                }
 
                var ts = typeof payload === 'number'
                            ? tasks.splice(0, payload)
                            : tasks.splice(0, tasks.length);
 
                var ds = _map(ts, function (task) {
                    return task.data;
                });
 
                if(cargo.empty) cargo.empty();
                working = true;
                worker(ds, function () {
                    working = false;
 
                    var args = arguments;
                    _each(ts, function (data) {
                        if (data.callback) {
                            data.callback.apply(null, args);
                        }
                    });
 
                    process();
                });
            },
            length: function () {
                return tasks.length;
            },
            running: function () {
                return working;
            }
        };
        return cargo;
    };
 
    var _console_fn = function (name) {
        return function (fn) {
            var args = Array.prototype.slice.call(arguments, 1);
            fn.apply(null, args.concat([function (err) {
                var args = Array.prototype.slice.call(arguments, 1);
                if (typeof console !== 'undefined') {
                    if (err) {
                        if (console.error) {
                            console.error(err);
                        }
                    }
                    else if (console[name]) {
                        _each(args, function (x) {
                            console[name](x);
                        });
                    }
                }
            }]));
        };
    };
    async.log = _console_fn('log');
    async.dir = _console_fn('dir');
    /*async.info = _console_fn('info');
    async.warn = _console_fn('warn');
    async.error = _console_fn('error');*/
 
    async.memoize = function (fn, hasher) {
        var memo = {};
        var queues = {};
        hasher = hasher || function (x) {
            return x;
        };
        var memoized = function () {
            var args = Array.prototype.slice.call(arguments);
            var callback = args.pop();
            var key = hasher.apply(null, args);
            if (key in memo) {
                async.nextTick(function () {
                    callback.apply(null, memo[key]);
                });
            }
            else if (key in queues) {
                queues[key].push(callback);
            }
            else {
                queues[key] = [callback];
                fn.apply(null, args.concat([function () {
                    memo[key] = arguments;
                    var q = queues[key];
                    delete queues[key];
                    for (var i = 0, l = q.length; i < l; i++) {
                      q[i].apply(null, arguments);
                    }
                }]));
            }
        };
        memoized.memo = memo;
        memoized.unmemoized = fn;
        return memoized;
    };
 
    async.unmemoize = function (fn) {
      return function () {
        return (fn.unmemoized || fn).apply(null, arguments);
      };
    };
 
    async.times = function (count, iterator, callback) {
        var counter = [];
        for (var i = 0; i < count; i++) {
            counter.push(i);
        }
        return async.map(counter, iterator, callback);
    };
 
    async.timesSeries = function (count, iterator, callback) {
        var counter = [];
        for (var i = 0; i < count; i++) {
            counter.push(i);
        }
        return async.mapSeries(counter, iterator, callback);
    };
 
    async.seq = function (/* functions... */) {
        var fns = arguments;
        return function () {
            var that = this;
            var args = Array.prototype.slice.call(arguments);
            var callback = args.pop();
            async.reduce(fns, args, function (newargs, fn, cb) {
                fn.apply(that, newargs.concat([function () {
                    var err = arguments[0];
                    var nextargs = Array.prototype.slice.call(arguments, 1);
                    cb(err, nextargs);
                }]))
            },
            function (err, results) {
                callback.apply(that, [err].concat(results));
            });
        };
    };
 
    async.compose = function (/* functions... */) {
      return async.seq.apply(null, Array.prototype.reverse.call(arguments));
    };
 
    var _applyEach = function (eachfn, fns /*args...*/) {
        var go = function () {
            var that = this;
            var args = Array.prototype.slice.call(arguments);
            var callback = args.pop();
            return eachfn(fns, function (fn, cb) {
                fn.apply(that, args.concat([cb]));
            },
            callback);
        };
        if (arguments.length > 2) {
            var args = Array.prototype.slice.call(arguments, 2);
            return go.apply(this, args);
        }
        else {
            return go;
        }
    };
    async.applyEach = doParallel(_applyEach);
    async.applyEachSeries = doSeries(_applyEach);
 
    async.forever = function (fn, callback) {
        function next(err) {
            if (err) {
                if (callback) {
                    return callback(err);
                }
                throw err;
            }
            fn(next);
        }
        next();
    };
 
    // Node.js
    Eif (typeof module !== 'undefined' && module.exports) {
        module.exports = async;
    }
    // AMD / RequireJS
    else if (typeof define !== 'undefined' && define.amd) {
        define([], function () {
            return async;
        });
    }
    // included directly via <script> tag
    else {
        root.async = async;
    }
 
}());
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/lib/

Statements: 16.94% (104 / 614)      Branches: 1.81% (6 / 332)      Functions: 4.62% (3 / 65)      Lines: 17.08% (104 / 609)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/bunyan/lib/
File Statements Branches Functions Lines
bunyan.js 16.94% (104 / 614) 1.81% (6 / 332) 4.62% (3 / 65) 17.08% (104 / 609)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/lib/bunyan.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/lib/bunyan.js

Statements: 16.94% (104 / 614)      Branches: 1.81% (6 / 332)      Functions: 4.62% (3 / 65)      Lines: 17.08% (104 / 609)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436                    1             1     1         1     1 1 1 1 1   1       1   1 1       1         1   1           1 1   1   1   1                     1                               1 1                                                                                         1                                                 1                           1                   1     1     1 1                             1 1 1 1 1 1   1               1 1 6       1 1             1                                                                                           1                                                                                                                                                                                                                                                                                                                                                                   1                                       1                                                                                                                                                                 1                                                                                           1                                           1                                                                                                                 1                                                                                         1                                                                                           1                                                                     1                                                                                                                   1 6     1                                                                                                                                                                                                                               1 1 1 1 1 1                 1     1                                   1                                     1                           1                               1                                   1   1                                                                                                                         1   1                                   1                                                                                                                                                               1                                           1                         1                                                           1                                   1                 1       1       1                               1             1   1                       1           1         1             1   1 1 1 1 1 1 1 1 1   1 1   1       1 1         1    
/**
 * Copyright (c) 2014 Trent Mick. All rights reserved.
 * Copyright (c) 2014 Joyent Inc. All rights reserved.
 *
 * The bunyan logging library for node.js.
 *
 * -*- mode: js -*-
 * vim: expandtab:ts=4:sw=4
 */
 
var VERSION = '1.3.5';
 
// Bunyan log format version. This becomes the 'v' field on all log records.
// `0` is until I release a version '1.0.0' of node-bunyan. Thereafter,
// starting with `1`, this will be incremented if there is any backward
// incompatible change to the log record format. Details will be in
// 'CHANGES.md' (the change log).
var LOG_VERSION = 0;
 
 
var xxx = function xxx(s) {     // internal dev/debug logging
    var args = ['XX' + 'X: '+s].concat(
        Array.prototype.slice.call(arguments, 1));
    console.error.apply(this, args);
};
var xxx = function xxx() {};  // comment out to turn on debug logging
 
 
var os = require('os');
var fs = require('fs');
var util = require('util');
var assert = require('assert');
try {
    /* Use `+ ''` to hide this import from browserify. */
    var dtrace = require('dtrace-provider' + '');
} catch (e) {
    dtrace = null;
}
var EventEmitter = require('events').EventEmitter;
 
try {
    var safeJsonStringify = require('safe-json-stringify');
} catch (e) {
    safeJsonStringify = null;
}
Iif (process.env.BUNYAN_TEST_NO_SAFE_JSON_STRINGIFY) {
    safeJsonStringify = null;
}
 
// The 'mv' module is required for rotating-file stream support.
try {
    /* Use `+ ''` to hide this import from browserify. */
    var mv = require('mv' + '');
} catch (e) {
    mv = null;
}
 
// Are we in the browser (e.g. running via browserify)?
var isBrowser = function () {
        return typeof (window) !== 'undefined' && this === window; }();
 
try {
    /* Use `+ ''` to hide this import from browserify. */
    var sourceMapSupport = require('source-map-support' + '');
} catch (_) {
    sourceMapSupport = null;
}
 
 
 
//---- Internal support stuff
 
/**
 * A shallow copy of an object. Bunyan logging attempts to never cause
 * exceptions, so this function attempts to handle non-objects gracefully.
 */
function objCopy(obj) {
    if (obj == null) {  // null or undefined
        return obj;
    } else if (Array.isArray(obj)) {
        return obj.slice();
    } else if (typeof (obj) === 'object') {
        var copy = {};
        Object.keys(obj).forEach(function (k) {
            copy[k] = obj[k];
        });
        return copy;
    } else {
        return obj;
    }
}
 
var format = util.format;
Iif (!format) {
    // If node < 0.6, then use its `util.format`:
    // <https://github.com/joyent/node/blob/master/lib/util.js#L22>:
    var inspect = util.inspect;
    var formatRegExp = /%[sdj%]/g;
    format = function format(f) {
        if (typeof (f) !== 'string') {
            var objects = [];
            for (var i = 0; i < arguments.length; i++) {
                objects.push(inspect(arguments[i]));
            }
            return objects.join(' ');
        }
 
        var i = 1;
        var args = arguments;
        var len = args.length;
        var str = String(f).replace(formatRegExp, function (x) {
            if (i >= len)
                return x;
            switch (x) {
                case '%s': return String(args[i++]);
                case '%d': return Number(args[i++]);
                case '%j': return JSON.stringify(args[i++], safeCycles());
                case '%%': return '%';
                default:
                    return x;
            }
        });
        for (var x = args[i]; i < len; x = args[++i]) {
            if (x === null || typeof (x) !== 'object') {
                str += ' ' + x;
            } else {
                str += ' ' + inspect(x);
            }
        }
        return str;
    };
}
 
 
/**
 * Gather some caller info 3 stack levels up.
 * See <http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi>.
 */
function getCaller3Info() {
    var obj = {};
    var saveLimit = Error.stackTraceLimit;
    var savePrepare = Error.prepareStackTrace;
    Error.stackTraceLimit = 3;
    Error.captureStackTrace(this, getCaller3Info);
 
    Error.prepareStackTrace = function (_, stack) {
        var caller = stack[2];
        if (sourceMapSupport) {
            caller = sourceMapSupport.wrapCallSite(caller);
        }
        obj.file = caller.getFileName();
        obj.line = caller.getLineNumber();
        var func = caller.getFunctionName();
        if (func)
            obj.func = func;
    };
    this.stack;
    Error.stackTraceLimit = saveLimit;
    Error.prepareStackTrace = savePrepare;
    return obj;
}
 
 
function _indent(s, indent) {
    if (!indent) indent = '    ';
    var lines = s.split(/\r?\n/g);
    return indent + lines.join('\n' + indent);
}
 
 
/**
 * Warn about an bunyan processing error.
 *
 * @param msg {String} Message with which to warn.
 * @param dedupKey {String} Optional. A short string key for this warning to
 *      have its warning only printed once.
 */
function _warn(msg, dedupKey) {
    assert.ok(msg);
    if (dedupKey) {
        if (_warned[dedupKey]) {
            return;
        }
        _warned[dedupKey] = true;
    }
    process.stderr.write(msg + '\n');
}
function _haveWarned(dedupKey) {
    return _warned[dedupKey];
}
var _warned = {};
 
 
function ConsoleRawStream() {}
ConsoleRawStream.prototype.write = function (rec) {
    if (rec.level < INFO) {
        console.log(rec);
    } else if (rec.level < WARN) {
        console.info(rec);
    } else if (rec.level < ERROR) {
        console.warn(rec);
    } else {
        console.error(rec);
    }
};
 
 
//---- Levels
 
var TRACE = 10;
var DEBUG = 20;
var INFO = 30;
var WARN = 40;
var ERROR = 50;
var FATAL = 60;
 
var levelFromName = {
    'trace': TRACE,
    'debug': DEBUG,
    'info': INFO,
    'warn': WARN,
    'error': ERROR,
    'fatal': FATAL
};
var nameFromLevel = {};
Object.keys(levelFromName).forEach(function (name) {
    nameFromLevel[levelFromName[name]] = name;
});
 
// Dtrace probes.
var dtp = undefined;
var probes = dtrace && {};
 
/**
 * Resolve a level number, name (upper or lowercase) to a level number value.
 *
 * @api public
 */
function resolveLevel(nameOrNum) {
    var level = (typeof (nameOrNum) === 'string'
            ? levelFromName[nameOrNum.toLowerCase()]
            : nameOrNum);
    return level;
}
 
 
 
//---- Logger class
 
/**
 * Create a Logger instance.
 *
 * @param options {Object} See documentation for full details. At minimum
 *    this must include a 'name' string key. Configuration keys:
 *      - `streams`: specify the logger output streams. This is an array of
 *        objects with these fields:
 *          - `type`: The stream type. See README.md for full details.
 *            Often this is implied by the other fields. Examples are
 *            'file', 'stream' and "raw".
 *          - `level`: Defaults to 'info'.
 *          - `path` or `stream`: The specify the file path or writeable
 *            stream to which log records are written. E.g.
 *            `stream: process.stdout`.
 *          - `closeOnExit` (boolean): Optional. Default is true for a
 *            'file' stream when `path` is given, false otherwise.
 *        See README.md for full details.
 *      - `level`: set the level for a single output stream (cannot be used
 *        with `streams`)
 *      - `stream`: the output stream for a logger with just one, e.g.
 *        `process.stdout` (cannot be used with `streams`)
 *      - `serializers`: object mapping log record field names to
 *        serializing functions. See README.md for details.
 *      - `src`: Boolean (default false). Set true to enable 'src' automatic
 *        field with log call source info.
 *    All other keys are log record fields.
 *
 * An alternative *internal* call signature is used for creating a child:
 *    new Logger(<parent logger>, <child options>[, <child opts are simple>]);
 *
 * @param _childSimple (Boolean) An assertion that the given `_childOptions`
 *    (a) only add fields (no config) and (b) no serialization handling is
 *    required for them. IOW, this is a fast path for frequent child
 *    creation.
 */
function Logger(options, _childOptions, _childSimple) {
    xxx('Logger start:', options)
    if (!(this instanceof Logger)) {
        return new Logger(options, _childOptions);
    }
 
    // Input arg validation.
    var parent;
    if (_childOptions !== undefined) {
        parent = options;
        options = _childOptions;
        if (!(parent instanceof Logger)) {
            throw new TypeError(
                'invalid Logger creation: do not pass a second arg');
        }
    }
    if (!options) {
        throw new TypeError('options (object) is required');
    }
    if (!parent) {
        if (!options.name) {
            throw new TypeError('options.name (string) is required');
        }
    } else {
        if (options.name) {
            throw new TypeError(
                'invalid options.name: child cannot set logger name');
        }
    }
    if (options.stream && options.streams) {
        throw new TypeError('cannot mix "streams" and "stream" options');
    }
    if (options.streams && !Array.isArray(options.streams)) {
        throw new TypeError('invalid options.streams: must be an array')
    }
    if (options.serializers && (typeof (options.serializers) !== 'object' ||
            Array.isArray(options.serializers))) {
        throw new TypeError('invalid options.serializers: must be an object')
    }
 
    EventEmitter.call(this);
 
    // Fast path for simple child creation.
    if (parent && _childSimple) {
        // `_isSimpleChild` is a signal to stream close handling that this child
        // owns none of its streams.
        this._isSimpleChild = true;
 
        this._level = parent._level;
        this.streams = parent.streams;
        this.serializers = parent.serializers;
        this.src = parent.src;
        var fields = this.fields = {};
        var parentFieldNames = Object.keys(parent.fields);
        for (var i = 0; i < parentFieldNames.length; i++) {
            var name = parentFieldNames[i];
            fields[name] = parent.fields[name];
        }
        var names = Object.keys(options);
        for (var i = 0; i < names.length; i++) {
            var name = names[i];
            fields[name] = options[name];
        }
        return;
    }
 
    // Null values.
    var self = this;
    if (parent) {
        this._level = parent._level;
        this.streams = [];
        for (var i = 0; i < parent.streams.length; i++) {
            var s = objCopy(parent.streams[i]);
            s.closeOnExit = false; // Don't own parent stream.
            this.streams.push(s);
        }
        this.serializers = objCopy(parent.serializers);
        this.src = parent.src;
        this.fields = objCopy(parent.fields);
        if (options.level) {
            this.level(options.level);
        }
    } else {
        this._level = Number.POSITIVE_INFINITY;
        this.streams = [];
        this.serializers = null;
        this.src = false;
        this.fields = {};
    }
 
    if (!dtp && dtrace) {
        dtp = dtrace.createDTraceProvider('bunyan');
 
        for (var level in levelFromName) {
            var probe;
 
            probes[levelFromName[level]] = probe =
                dtp.addProbe('log-' + level, 'char *');
 
            // Explicitly add a reference to dtp to prevent it from being GC'd
            probe.dtp = dtp;
        }
 
        dtp.enable();
    }
 
    // Handle *config* options (i.e. options that are not just plain data
    // for log records).
    if (options.stream) {
        self.addStream({
            type: 'stream',
            stream: options.stream,
            closeOnExit: false,
            level: options.level
        });
    } else if (options.streams) {
        options.streams.forEach(function (s) {
            self.addStream(s, options.level);
        });
    } else if (parent && options.level) {
        this.level(options.level);
    } else if (!parent) {
        if (isBrowser) {
            /*
             * In the browser we'll be emitting to console.log by default.
             * Any console.log worth its salt these days can nicely render
             * and introspect objects (e.g. the Firefox and Chrome console)
             * so let's emit the raw log record. Are there browsers for which
             * that breaks things?
             */
            self.addStream({
                type: 'raw',
                stream: new ConsoleRawStream(),
                closeOnExit: false,
                level: options.level
            });
        } else {
            self.addStream({
                type: 'stream',
                stream: process.stdout,
                closeOnExit: false,
                level: options.level
            });
        }
    }
    if (options.serializers) {
        self.addSerializers(options.serializers);
    }
    if (options.src) {
        this.src = true;
    }
    xxx('Logger: ', self)
 
    // Fields.
    // These are the default fields for log records (minus the attributes
    // removed in this constructor). To allow storing raw log records
    // (unrendered), `this.fields` must never be mutated. Create a copy for
    // any changes.
    var fields = objCopy(options);
    delete fields.stream;
    delete fields.level;
    delete fields.streams;
    delete fields.serializers;
    delete fields.src;
    if (this.serializers) {
        this._applySerializers(fields);
    }
    if (!fields.hostname) {
        fields.hostname = os.hostname();
    }
    if (!fields.pid) {
        fields.pid = process.pid;
    }
    Object.keys(fields).forEach(function (k) {
        self.fields[k] = fields[k];
    });
}
 
util.inherits(Logger, EventEmitter);
 
 
/**
 * Add a stream
 *
 * @param stream {Object}. Object with these fields:
 *    - `type`: The stream type. See README.md for full details.
 *      Often this is implied by the other fields. Examples are
 *      'file', 'stream' and "raw".
 *    - `path` or `stream`: The specify the file path or writeable
 *      stream to which log records are written. E.g.
 *      `stream: process.stdout`.
 *    - `level`: Optional. Falls back to `defaultLevel`.
 *    - `closeOnExit` (boolean): Optional. Default is true for a
 *      'file' stream when `path` is given, false otherwise.
 *    See README.md for full details.
 * @param defaultLevel {Number|String} Optional. A level to use if
 *      `stream.level` is not set. If neither is given, this defaults to INFO.
 */
Logger.prototype.addStream = function addStream(s, defaultLevel) {
    var self = this;
    if (defaultLevel === null || defaultLevel === undefined) {
        defaultLevel = INFO;
    }
 
    s = objCopy(s);
 
    // Implicit 'type' from other args.
    var type = s.type;
    if (!s.type) {
        if (s.stream) {
            s.type = 'stream';
        } else if (s.path) {
            s.type = 'file'
        }
    }
    s.raw = (s.type === 'raw');  // PERF: Allow for faster check in `_emit`.
 
    if (s.level) {
        s.level = resolveLevel(s.level);
    } else {
        s.level = resolveLevel(defaultLevel);
    }
    if (s.level < self._level) {
        self._level = s.level;
    }
 
    switch (s.type) {
    case 'stream':
        if (!s.closeOnExit) {
            s.closeOnExit = false;
        }
        break;
    case 'file':
        if (!s.stream) {
            s.stream = fs.createWriteStream(s.path,
                                            {flags: 'a', encoding: 'utf8'});
            s.stream.on('error', function (err) {
                self.emit('error', err, s);
            });
            if (!s.closeOnExit) {
                s.closeOnExit = true;
            }
        } else {
            if (!s.closeOnExit) {
                s.closeOnExit = false;
            }
        }
        break;
    case 'rotating-file':
        assert.ok(!s.stream,
                  '"rotating-file" stream should not give a "stream"');
        assert.ok(s.path);
        assert.ok(mv, '"rotating-file" stream type is not supported: '
                      + 'missing "mv" module');
        s.stream = new RotatingFileStream(s);
        if (!s.closeOnExit) {
            s.closeOnExit = true;
        }
        break;
    case 'raw':
        if (!s.closeOnExit) {
            s.closeOnExit = false;
        }
        break;
    default:
        throw new TypeError('unknown stream type "' + s.type + '"');
    }
 
    self.streams.push(s);
    delete self.haveNonRawStreams;  // reset
}
 
 
/**
 * Add serializers
 *
 * @param serializers {Object} Optional. Object mapping log record field names
 *    to serializing functions. See README.md for details.
 */
Logger.prototype.addSerializers = function addSerializers(serializers) {
    var self = this;
 
    if (!self.serializers) {
        self.serializers = {};
    }
    Object.keys(serializers).forEach(function (field) {
        var serializer = serializers[field];
        if (typeof (serializer) !== 'function') {
            throw new TypeError(format(
                'invalid serializer for "%s" field: must be a function',
                field));
        } else {
            self.serializers[field] = serializer;
        }
    });
}
 
 
 
/**
 * Create a child logger, typically to add a few log record fields.
 *
 * This can be useful when passing a logger to a sub-component, e.g. a
 * 'wuzzle' component of your service:
 *
 *    var wuzzleLog = log.child({component: 'wuzzle'})
 *    var wuzzle = new Wuzzle({..., log: wuzzleLog})
 *
 * Then log records from the wuzzle code will have the same structure as
 * the app log, *plus the component='wuzzle' field*.
 *
 * @param options {Object} Optional. Set of options to apply to the child.
 *    All of the same options for a new Logger apply here. Notes:
 *      - The parent's streams are inherited and cannot be removed in this
 *        call. Any given `streams` are *added* to the set inherited from
 *        the parent.
 *      - The parent's serializers are inherited, though can effectively be
 *        overwritten by using duplicate keys.
 *      - Can use `level` to set the level of the streams inherited from
 *        the parent. The level for the parent is NOT affected.
 * @param simple {Boolean} Optional. Set to true to assert that `options`
 *    (a) only add fields (no config) and (b) no serialization handling is
 *    required for them. IOW, this is a fast path for frequent child
 *    creation. See 'tools/timechild.js' for numbers.
 */
Logger.prototype.child = function (options, simple) {
    return new (this.constructor)(this, options || {}, simple);
}
 
 
/**
 * A convenience method to reopen 'file' streams on a logger. This can be
 * useful with external log rotation utilities that move and re-open log files
 * (e.g. logrotate on Linux, logadm on SmartOS/Illumos). Those utilities
 * typically have rotation options to copy-and-truncate the log file, but
 * you may not want to use that. An alternative is to do this in your
 * application:
 *
 *      var log = bunyan.createLogger(...);
 *      ...
 *      process.on('SIGUSR2', function () {
 *          log.reopenFileStreams();
 *      });
 *      ...
 *
 * See <https://github.com/trentm/node-bunyan/issues/104>.
 */
Logger.prototype.reopenFileStreams = function () {
    var self = this;
    self.streams.forEach(function (s) {
        if (s.type === 'file') {
            if (s.stream) {
                // Not sure if typically would want this, or more immediate
                // `s.stream.destroy()`.
                s.stream.end();
                s.stream.destroySoon();
                delete s.stream;
            }
            s.stream = fs.createWriteStream(s.path,
                {flags: 'a', encoding: 'utf8'});
            s.stream.on('error', function (err) {
                self.emit('error', err, s);
            });
        }
    });
};
 
 
/* BEGIN JSSTYLED */
/**
 * Close this logger.
 *
 * This closes streams (that it owns, as per 'endOnClose' attributes on
 * streams), etc. Typically you **don't** need to bother calling this.
Logger.prototype.close = function () {
    if (this._closed) {
        return;
    }
    if (!this._isSimpleChild) {
        self.streams.forEach(function (s) {
            if (s.endOnClose) {
                xxx('closing stream s:', s);
                s.stream.end();
                s.endOnClose = false;
            }
        });
    }
    this._closed = true;
}
 */
/* END JSSTYLED */
 
 
/**
 * Get/set the level of all streams on this logger.
 *
 * Get Usage:
 *    // Returns the current log level (lowest level of all its streams).
 *    log.level() -> INFO
 *
 * Set Usage:
 *    log.level(INFO)       // set all streams to level INFO
 *    log.level('info')     // can use 'info' et al aliases
 */
Logger.prototype.level = function level(value) {
    if (value === undefined) {
        return this._level;
    }
    var newLevel = resolveLevel(value);
    var len = this.streams.length;
    for (var i = 0; i < len; i++) {
        this.streams[i].level = newLevel;
    }
    this._level = newLevel;
}
 
 
/**
 * Get/set the level of a particular stream on this logger.
 *
 * Get Usage:
 *    // Returns an array of the levels of each stream.
 *    log.levels() -> [TRACE, INFO]
 *
 *    // Returns a level of the identified stream.
 *    log.levels(0) -> TRACE      // level of stream at index 0
 *    log.levels('foo')           // level of stream with name 'foo'
 *
 * Set Usage:
 *    log.levels(0, INFO)         // set level of stream 0 to INFO
 *    log.levels(0, 'info')       // can use 'info' et al aliases
 *    log.levels('foo', WARN)     // set stream named 'foo' to WARN
 *
 * Stream names: When streams are defined, they can optionally be given
 * a name. For example,
 *       log = new Logger({
 *         streams: [
 *           {
 *             name: 'foo',
 *             path: '/var/log/my-service/foo.log'
 *             level: 'trace'
 *           },
 *         ...
 *
 * @param name {String|Number} The stream index or name.
 * @param value {Number|String} The level value (INFO) or alias ('info').
 *    If not given, this is a 'get' operation.
 * @throws {Error} If there is no stream with the given name.
 */
Logger.prototype.levels = function levels(name, value) {
    if (name === undefined) {
        assert.equal(value, undefined);
        return this.streams.map(
            function (s) { return s.level });
    }
    var stream;
    if (typeof (name) === 'number') {
        stream = this.streams[name];
        if (stream === undefined) {
            throw new Error('invalid stream index: ' + name);
        }
    } else {
        var len = this.streams.length;
        for (var i = 0; i < len; i++) {
            var s = this.streams[i];
            if (s.name === name) {
                stream = s;
                break;
            }
        }
        if (!stream) {
            throw new Error(format('no stream with name "%s"', name));
        }
    }
    if (value === undefined) {
        return stream.level;
    } else {
        var newLevel = resolveLevel(value);
        stream.level = newLevel;
        if (newLevel < this._level) {
            this._level = newLevel;
        }
    }
}
 
 
/**
 * Apply registered serializers to the appropriate keys in the given fields.
 *
 * Pre-condition: This is only called if there is at least one serializer.
 *
 * @param fields (Object) The log record fields.
 * @param excludeFields (Object) Optional mapping of keys to `true` for
 *    keys to NOT apply a serializer.
 */
Logger.prototype._applySerializers = function (fields, excludeFields) {
    var self = this;
 
    xxx('_applySerializers: excludeFields', excludeFields);
 
    // Check each serializer against these (presuming number of serializers
    // is typically less than number of fields).
    Object.keys(this.serializers).forEach(function (name) {
        if (fields[name] === undefined ||
            (excludeFields && excludeFields[name]))
        {
            return;
        }
        xxx('_applySerializers; apply to "%s" key', name)
        try {
            fields[name] = self.serializers[name](fields[name]);
        } catch (err) {
            _warn(format('bunyan: ERROR: Exception thrown from the "%s" '
                + 'Bunyan serializer. This should never happen. This is a bug'
                + 'in that serializer function.\n%s',
                name, err.stack || err));
            fields[name] = format('(Error in Bunyan log "%s" serializer '
                + 'broke field. See stderr for details.)', name);
        }
    });
}
 
 
/**
 * Emit a log record.
 *
 * @param rec {log record}
 * @param noemit {Boolean} Optional. Set to true to skip emission
 *      and just return the JSON string.
 */
Logger.prototype._emit = function (rec, noemit) {
    var i;
 
    // Lazily determine if this Logger has non-'raw' streams. If there are
    // any, then we need to stringify the log record.
    if (this.haveNonRawStreams === undefined) {
        this.haveNonRawStreams = false;
        for (i = 0; i < this.streams.length; i++) {
            if (!this.streams[i].raw) {
                this.haveNonRawStreams = true;
                break;
            }
        }
    }
 
    // Stringify the object. Attempt to warn/recover on error.
    var str;
    if (noemit || this.haveNonRawStreams) {
        try {
            str = JSON.stringify(rec, safeCycles()) + '\n';
        } catch (e) {
            if (safeJsonStringify) {
                str = safeJsonStringify(rec) + '\n';
            } else {
                var dedupKey = e.stack.split(/\n/g, 2).join('\n');
                _warn('bunyan: ERROR: Exception in '
                    + '`JSON.stringify(rec)`. You can install the '
                    + '"safe-json-stringify" module to have Bunyan fallback '
                    + 'to safer stringification. Record:\n'
                    + _indent(format('%s\n%s', util.inspect(rec), e.stack)),
                    dedupKey);
                str = format('(Exception in JSON.stringify(rec): %j. '
                    + 'See stderr for details.)\n', e.message);
            }
        }
    }
 
    if (noemit)
        return str;
 
    var level = rec.level;
    for (i = 0; i < this.streams.length; i++) {
        var s = this.streams[i];
        if (s.level <= level) {
            xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j',
                rec.msg, s.type, s.level, level, rec);
            s.stream.write(s.raw ? rec : str);
        }
    };
 
    return str;
}
 
 
/**
 * Build a log emitter function for level minLevel. I.e. this is the
 * creator of `log.info`, `log.error`, etc.
 */
function mkLogEmitter(minLevel) {
    return function () {
        var log = this;
 
        function mkRecord(args) {
            var excludeFields;
            if (args[0] instanceof Error) {
                // `log.<level>(err, ...)`
                fields = {
                    // Use this Logger's err serializer, if defined.
                    err: (log.serializers && log.serializers.err
                        ? log.serializers.err(args[0])
                        : Logger.stdSerializers.err(args[0]))
                };
                excludeFields = {err: true};
                if (args.length === 1) {
                    msgArgs = [fields.err.message];
                } else {
                    msgArgs = Array.prototype.slice.call(args, 1);
                }
            } else if (typeof (args[0]) !== 'object' && args[0] !== null ||
                       Array.isArray(args[0])) {
                // `log.<level>(msg, ...)`
                fields = null;
                msgArgs = Array.prototype.slice.call(args);
            } else if (Buffer.isBuffer(args[0])) {  // `log.<level>(buf, ...)`
                // Almost certainly an error, show `inspect(buf)`. See bunyan
                // issue #35.
                fields = null;
                msgArgs = Array.prototype.slice.call(args);
                msgArgs[0] = util.inspect(msgArgs[0]);
            } else {  // `log.<level>(fields, msg, ...)`
                fields = args[0];
                msgArgs = Array.prototype.slice.call(args, 1);
            }
 
            // Build up the record object.
            var rec = objCopy(log.fields);
            var level = rec.level = minLevel;
            var recFields = (fields ? objCopy(fields) : null);
            if (recFields) {
                if (log.serializers) {
                    log._applySerializers(recFields, excludeFields);
                }
                Object.keys(recFields).forEach(function (k) {
                    rec[k] = recFields[k];
                });
            }
            rec.msg = format.apply(log, msgArgs);
            if (!rec.time) {
                rec.time = (new Date());
            }
            // Get call source info
            if (log.src && !rec.src) {
                rec.src = getCaller3Info()
            }
            rec.v = LOG_VERSION;
 
            return rec;
        };
 
        var fields = null;
        var msgArgs = arguments;
        var str = null;
        var rec = null;
        if (! this._emit) {
            /*
             * Show this invalid Bunyan usage warning *once*.
             *
             * See <https://github.com/trentm/node-bunyan/issues/100> for
             * an example of how this can happen.
             */
            var dedupKey = 'unbound';
            if (!_haveWarned[dedupKey]) {
                var caller = getCaller3Info();
                _warn(format('bunyan usage error: %s:%s: attempt to log '
                    + 'with an unbound log method: `this` is: %s',
                    caller.file, caller.line, util.inspect(this)),
                    dedupKey);
            }
            return;
        } else if (arguments.length === 0) {   // `log.<level>()`
            return (this._level <= minLevel);
        } else if (this._level > minLevel) {
            /* pass through */
        } else {
            rec = mkRecord(msgArgs);
            str = this._emit(rec);
        }
        probes && probes[minLevel].fire(function () {
                return [ str ||
                    (rec && log._emit(rec, true)) ||
                    log._emit(mkRecord(msgArgs), true) ];
        });
    }
}
 
 
/**
 * The functions below log a record at a specific level.
 *
 * Usages:
 *    log.<level>()  -> boolean is-trace-enabled
 *    log.<level>(<Error> err, [<string> msg, ...])
 *    log.<level>(<string> msg, ...)
 *    log.<level>(<object> fields, <string> msg, ...)
 *
 * where <level> is the lowercase version of the log level. E.g.:
 *
 *    log.info()
 *
 * @params fields {Object} Optional set of additional fields to log.
 * @params msg {String} Log message. This can be followed by additional
 *    arguments that are handled like
 *    [util.format](http://nodejs.org/docs/latest/api/all.html#util.format).
 */
Logger.prototype.trace = mkLogEmitter(TRACE);
Logger.prototype.debug = mkLogEmitter(DEBUG);
Logger.prototype.info = mkLogEmitter(INFO);
Logger.prototype.warn = mkLogEmitter(WARN);
Logger.prototype.error = mkLogEmitter(ERROR);
Logger.prototype.fatal = mkLogEmitter(FATAL);
 
 
 
//---- Standard serializers
// A serializer is a function that serializes a JavaScript object to a
// JSON representation for logging. There is a standard set of presumed
// interesting objects in node.js-land.
 
Logger.stdSerializers = {};
 
// Serialize an HTTP request.
Logger.stdSerializers.req = function req(req) {
    if (!req || !req.connection)
        return req;
    return {
        method: req.method,
        url: req.url,
        headers: req.headers,
        remoteAddress: req.connection.remoteAddress,
        remotePort: req.connection.remotePort
    };
    // Trailers: Skipping for speed. If you need trailers in your app, then
    // make a custom serializer.
    //if (Object.keys(trailers).length > 0) {
    //  obj.trailers = req.trailers;
    //}
};
 
// Serialize an HTTP response.
Logger.stdSerializers.res = function res(res) {
    if (!res || !res.statusCode)
        return res;
    return {
        statusCode: res.statusCode,
        header: res._header
    }
};
 
 
/*
 * This function dumps long stack traces for exceptions having a cause()
 * method. The error classes from
 * [verror](https://github.com/davepacheco/node-verror) and
 * [restify v2.0](https://github.com/mcavage/node-restify) are examples.
 *
 * Based on `dumpException` in
 * https://github.com/davepacheco/node-extsprintf/blob/master/lib/extsprintf.js
 */
function getFullErrorStack(ex)
{
    var ret = ex.stack || ex.toString();
    if (ex.cause && typeof (ex.cause) === 'function') {
        var cex = ex.cause();
        if (cex) {
            ret += '\nCaused by: ' + getFullErrorStack(cex);
        }
    }
    return (ret);
}
 
// Serialize an Error object
// (Core error properties are enumerable in node 0.4, not in 0.6).
var errSerializer = Logger.stdSerializers.err = function err(err) {
    if (!err || !err.stack)
        return err;
    var obj = {
        message: err.message,
        name: err.name,
        stack: getFullErrorStack(err),
        code: err.code,
        signal: err.signal
    }
    return obj;
};
 
 
// A JSON stringifier that handles cycles safely.
// Usage: JSON.stringify(obj, safeCycles())
function safeCycles() {
    var seen = [];
    return function (key, val) {
        if (!val || typeof (val) !== 'object') {
            return val;
        }
        if (seen.indexOf(val) !== -1) {
            return '[Circular]';
        }
        seen.push(val);
        return val;
    };
}
 
 
/**
 * XXX
 */
Eif (mv) {
 
function RotatingFileStream(options) {
    this.path = options.path;
    this.stream = fs.createWriteStream(this.path,
        {flags: 'a', encoding: 'utf8'});
    this.count = (options.count == null ? 10 : options.count);
    assert.equal(typeof (this.count), 'number',
        format('rotating-file stream "count" is not a number: %j (%s) in %j',
            this.count, typeof (this.count), this));
    assert.ok(this.count >= 0,
        format('rotating-file stream "count" is not >= 0: %j in %j',
            this.count, this));
 
    // Parse `options.period`.
    if (options.period) {
        // <number><scope> where scope is:
        //    h   hours (at the start of the hour)
        //    d   days (at the start of the day, i.e. just after midnight)
        //    w   weeks (at the start of Sunday)
        //    m   months (on the first of the month)
        //    y   years (at the start of Jan 1st)
        // with special values 'hourly' (1h), 'daily' (1d), "weekly" (1w),
        // 'monthly' (1m) and 'yearly' (1y)
        var period = {
            'hourly': '1h',
            'daily': '1d',
            'weekly': '1w',
            'monthly': '1m',
            'yearly': '1y'
        }[options.period] || options.period;
        var m = /^([1-9][0-9]*)([hdwmy]|ms)$/.exec(period);
        if (!m) {
            throw new Error(format('invalid period: "%s"', options.period));
        }
        this.periodNum = Number(m[1]);
        this.periodScope = m[2];
    } else {
        this.periodNum = 1;
        this.periodScope = 'd';
    }
 
    // TODO: template support for backup files
    // template: <path to which to rotate>
    //      default is %P.%n
    //      '/var/log/archive/foo.log'  -> foo.log.%n
    //      '/var/log/archive/foo.log.%n'
    //      codes:
    //          XXX support strftime codes (per node version of those)
    //              or whatever module. Pick non-colliding for extra
    //              codes
    //          %P      `path` base value
    //          %n      integer number of rotated log (1,2,3,...)
    //          %d      datetime in YYYY-MM-DD_HH-MM-SS
    //                      XXX what should default date format be?
    //                          prior art? Want to avoid ':' in
    //                          filenames (illegal on Windows for one).
 
    this.rotQueue = [];
    this.rotating = false;
    this._setupNextRot();
}
 
util.inherits(RotatingFileStream, EventEmitter);
 
RotatingFileStream.prototype._setupNextRot = function () {
    var self = this;
    this.rotAt = this._nextRotTime();
    var delay = this.rotAt - Date.now();
    // Cap timeout to Node's max setTimeout, see
    // <https://github.com/joyent/node/issues/8656>.
    var TIMEOUT_MAX = 2147483647; // 2^31-1
    if (delay > TIMEOUT_MAX) {
        delay = TIMEOUT_MAX;
    }
    this.timeout = setTimeout(
        function () { self.rotate(); },
        delay);
    if (typeof (this.timeout.unref) === 'function') {
        this.timeout.unref();
    }
}
 
RotatingFileStream.prototype._nextRotTime = function _nextRotTime(first) {
    var _DEBUG = false;
    if (_DEBUG)
        console.log('-- _nextRotTime: %s%s', this.periodNum, this.periodScope);
    var d = new Date();
 
    if (_DEBUG) console.log('  now local: %s', d);
    if (_DEBUG) console.log('    now utc: %s', d.toISOString());
    var rotAt;
    switch (this.periodScope) {
    case 'ms':
        // Hidden millisecond period for debugging.
        if (this.rotAt) {
            rotAt = this.rotAt + this.periodNum;
        } else {
            rotAt = Date.now() + this.periodNum;
        }
        break;
    case 'h':
        if (this.rotAt) {
            rotAt = this.rotAt + this.periodNum * 60 * 60 * 1000;
        } else {
            // First time: top of the next hour.
            rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(),
                d.getUTCDate(), d.getUTCHours() + 1);
        }
        break;
    case 'd':
        if (this.rotAt) {
            rotAt = this.rotAt + this.periodNum * 24 * 60 * 60 * 1000;
        } else {
            // First time: start of tomorrow (i.e. at the coming midnight) UTC.
            rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(),
                d.getUTCDate() + 1);
        }
        break;
    case 'w':
        // Currently, always on Sunday morning at 00:00:00 (UTC).
        if (this.rotAt) {
            rotAt = this.rotAt + this.periodNum * 7 * 24 * 60 * 60 * 1000;
        } else {
            // First time: this coming Sunday.
            rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(),
                d.getUTCDate() + (7 - d.getUTCDay()));
        }
        break;
    case 'm':
        if (this.rotAt) {
            rotAt = Date.UTC(d.getUTCFullYear(),
                d.getUTCMonth() + this.periodNum, 1);
        } else {
            // First time: the start of the next month.
            rotAt = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1);
        }
        break;
    case 'y':
        if (this.rotAt) {
            rotAt = Date.UTC(d.getUTCFullYear() + this.periodNum, 0, 1);
        } else {
            // First time: the start of the next year.
            rotAt = Date.UTC(d.getUTCFullYear() + 1, 0, 1);
        }
        break;
    default:
        assert.fail(format('invalid period scope: "%s"', this.periodScope));
    }
 
    if (_DEBUG) {
        console.log('  **rotAt**: %s (utc: %s)', rotAt,
            new Date(rotAt).toUTCString());
        var now = Date.now();
        console.log('        now: %s (%sms == %smin == %sh to go)',
            now,
            rotAt - now,
            (rotAt-now)/1000/60,
            (rotAt-now)/1000/60/60);
    }
    return rotAt;
};
 
RotatingFileStream.prototype.rotate = function rotate() {
    // XXX What about shutdown?
    var self = this;
    var _DEBUG = false;
 
    // If rotation period is > ~25 days, we have to break into multiple
    // setTimeout's. See <https://github.com/joyent/node/issues/8656>.
    if (self.rotAt && self.rotAt > Date.now()) {
        return self._setupNextRot();
    }
 
    if (_DEBUG) {
        console.log('-- [%s, pid=%s] rotating %s',
            new Date(), process.pid, self.path);
    }
    if (self.rotating) {
        throw new TypeError('cannot start a rotation when already rotating');
    }
    self.rotating = true;
 
    self.stream.end();  // XXX can do moves sync after this? test at high rate
 
    function del() {
        var toDel = self.path + '.' + String(n - 1);
        if (n === 0) {
            toDel = self.path;
        }
        n -= 1;
        if (_DEBUG) console.log('rm %s', toDel);
        fs.unlink(toDel, function (delErr) {
            //XXX handle err other than not exists
            moves();
        });
    }
 
    function moves() {
        if (self.count === 0 || n < 0) {
            return finish();
        }
        var before = self.path;
        var after = self.path + '.' + String(n);
        if (n > 0) {
            before += '.' + String(n - 1);
        }
        n -= 1;
        fs.exists(before, function (exists) {
            if (!exists) {
                moves();
            } else {
                if (_DEBUG) {
                    console.log('[pid %s] mv %s %s',
                        process.pid, before, after);
                }
                mv(before, after, function (mvErr) {
                    if (mvErr) {
                        self.emit('error', mvErr);
                        finish(); // XXX finish here?
                    } else {
                        moves();
                    }
                });
            }
        })
    }
 
    function finish() {
        if (_DEBUG) console.log('[pid %s] open %s', process.pid, self.path);
        self.stream = fs.createWriteStream(self.path,
            {flags: 'a', encoding: 'utf8'});
        var q = self.rotQueue, len = q.length;
        for (var i = 0; i < len; i++) {
            self.stream.write(q[i]);
        }
        self.rotQueue = [];
        self.rotating = false;
        self.emit('drain');
        self._setupNextRot();
    }
 
    var n = this.count;
    del();
};
 
RotatingFileStream.prototype.write = function write(s) {
    if (this.rotating) {
        this.rotQueue.push(s);
        return false;
    } else {
        return this.stream.write(s);
    }
};
 
RotatingFileStream.prototype.end = function end(s) {
    this.stream.end();
};
 
RotatingFileStream.prototype.destroy = function destroy(s) {
    this.stream.destroy();
};
 
RotatingFileStream.prototype.destroySoon = function destroySoon(s) {
    this.stream.destroySoon();
};
 
} /* if (mv) */
 
 
 
/**
 * RingBuffer is a Writable Stream that just stores the last N records in
 * memory.
 *
 * @param options {Object}, with the following fields:
 *
 *    - limit: number of records to keep in memory
 */
function RingBuffer(options) {
    this.limit = options && options.limit ? options.limit : 100;
    this.writable = true;
    this.records = [];
    EventEmitter.call(this);
}
 
util.inherits(RingBuffer, EventEmitter);
 
RingBuffer.prototype.write = function (record) {
    if (!this.writable)
        throw (new Error('RingBuffer has been ended already'));
 
    this.records.push(record);
 
    if (this.records.length > this.limit)
        this.records.shift();
 
    return (true);
};
 
RingBuffer.prototype.end = function () {
    if (arguments.length > 0)
        this.write.apply(this, Array.prototype.slice.call(arguments));
    this.writable = false;
};
 
RingBuffer.prototype.destroy = function () {
    this.writable = false;
    this.emit('close');
};
 
RingBuffer.prototype.destroySoon = function () {
    this.destroy();
};
 
 
//---- Exports
 
module.exports = Logger;
 
module.exports.TRACE = TRACE;
module.exports.DEBUG = DEBUG;
module.exports.INFO = INFO;
module.exports.WARN = WARN;
module.exports.ERROR = ERROR;
module.exports.FATAL = FATAL;
module.exports.resolveLevel = resolveLevel;
module.exports.levelFromName = levelFromName;
module.exports.nameFromLevel = nameFromLevel;
 
module.exports.VERSION = VERSION;
module.exports.LOG_VERSION = LOG_VERSION;
 
module.exports.createLogger = function createLogger(options) {
    return new Logger(options);
};
 
module.exports.RingBuffer = RingBuffer;
module.exports.RotatingFileStream = RotatingFileStream;
 
// Useful for custom `type == 'raw'` streams that may do JSON stringification
// of log records themselves. Usage:
//    var str = JSON.stringify(rec, bunyan.safeCycles());
module.exports.safeCycles = safeCycles;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/dtrace-provider/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/dtrace-provider/

Statements: 62.5% (15 / 24)      Branches: 55.56% (5 / 9)      Functions: 0% (0 / 7)      Lines: 62.5% (15 / 24)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/dtrace-provider/
File Statements Branches Functions Lines
dtrace-provider.js 62.5% (15 / 24) 55.56% (5 / 9) 0% (0 / 7) 62.5% (15 / 24)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/dtrace-provider/dtrace-provider.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/dtrace-provider/dtrace-provider.js

Statements: 62.5% (15 / 24)      Branches: 55.56% (5 / 9)      Functions: 0% (0 / 7)      Lines: 62.5% (15 / 24)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421   1 1         1 1 1   1   1 3 3           3               1 1     1 1            
var DTraceProvider;
 
function DTraceProviderStub() {}
DTraceProviderStub.prototype.addProbe = function(name) {
    var p = { 'fire': function () {} };
    this[name] = p;
    return (p);
};
DTraceProviderStub.prototype.enable = function() {};
DTraceProviderStub.prototype.fire = function() {};
DTraceProviderStub.prototype.disable = function() {};
 
var builds = ['Release', 'default', 'Debug'];
 
for (var i in builds) {
    try {
        var binding = require('./build/' + builds[i] + '/DTraceProviderBindings');
        DTraceProvider = binding.DTraceProvider;
        break;
    } catch (e) {
        // if the platform looks like it _should_ have DTrace
        // available, log a failure to load the bindings.
        Iif (process.platform == 'darwin' ||
            process.platform == 'solaris' ||
            process.platform == 'freebsd') {
            console.error(e);
        }
    }
}
 
Eif (!DTraceProvider) {
    DTraceProvider = DTraceProviderStub;
}
 
exports.DTraceProvider = DTraceProvider;
exports.createDTraceProvider = function(name, module) {
    if (arguments.length == 2)
        return (new exports.DTraceProvider(name, module));
    return (new exports.DTraceProvider(name));
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/

Statements: 17.81% (13 / 73)      Branches: 0% (0 / 34)      Functions: 0% (0 / 14)      Lines: 19.12% (13 / 68)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/
File Statements Branches Functions Lines
index.js 17.81% (13 / 73) 0% (0 / 34) 0% (0 / 14) 19.12% (13 / 68)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/index.js

Statements: 17.81% (13 / 73)      Branches: 0% (0 / 34)      Functions: 0% (0 / 14)      Lines: 19.12% (13 / 68)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 1071 1 1 1 1   1   1                             1             1                                                     1                                           1         1                           1                
var fs = require('fs');
var ncp = require('ncp').ncp;
var path = require('path');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
 
module.exports = mv;
 
function mv(source, dest, options, cb){
  if (typeof options === 'function') {
    cb = options;
    options = {};
  }
  var shouldMkdirp = !!options.mkdirp;
  var clobber = options.clobber !== false;
  var limit = options.limit || 16;
 
  if (shouldMkdirp) {
    mkdirs();
  } else {
    doRename();
  }
 
  function mkdirs() {
    mkdirp(path.dirname(dest), function(err) {
      if (err) return cb(err);
      doRename();
    });
  }
 
  function doRename() {
    if (clobber) {
      fs.rename(source, dest, function(err) {
        if (!err) return cb();
        if (err.code !== 'EXDEV') return cb(err);
        moveFileAcrossDevice(source, dest, clobber, limit, cb);
      });
    } else {
      fs.link(source, dest, function(err) {
        if (err) {
          if (err.code === 'EXDEV') {
            moveFileAcrossDevice(source, dest, clobber, limit, cb);
            return;
          }
          if (err.code === 'EISDIR' || err.code === 'EPERM') {
            moveDirAcrossDevice(source, dest, clobber, limit, cb);
            return;
          }
          cb(err);
          return;
        }
        fs.unlink(source, cb);
      });
    }
  }
}
 
function moveFileAcrossDevice(source, dest, clobber, limit, cb) {
  var outFlags = clobber ? 'w' : 'wx';
  var ins = fs.createReadStream(source);
  var outs = fs.createWriteStream(dest, {flags: outFlags});
  ins.on('error', function(err){
    ins.destroy();
    outs.destroy();
    outs.removeListener('close', onClose);
    if (err.code === 'EISDIR' || err.code === 'EPERM') {
      moveDirAcrossDevice(source, dest, clobber, limit, cb);
    } else {
      cb(err);
    }
  });
  outs.on('error', function(err){
    ins.destroy();
    outs.destroy();
    outs.removeListener('close', onClose);
    cb(err);
  });
  outs.once('close', onClose);
  ins.pipe(outs);
  function onClose(){
    fs.unlink(source, cb);
  }
}
 
function moveDirAcrossDevice(source, dest, clobber, limit, cb) {
  var options = {
    stopOnErr: true,
    clobber: false,
    limit: limit,
  };
  if (clobber) {
    rimraf(dest, function(err) {
      if (err) return cb(err);
      startNcp();
    });
  } else {
    startNcp();
  }
  function startNcp() {
    ncp(source, dest, options, function(errList) {
      if (errList) return cb(errList[0]);
      rimraf(source, cb);
    });
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/ncp/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/ncp/lib/

Statements: 14.62% (19 / 130)      Branches: 0% (0 / 85)      Functions: 0% (0 / 31)      Lines: 14.84% (19 / 128)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/ncp/lib/
File Statements Branches Functions Lines
ncp.js 14.62% (19 / 130) 0% (0 / 85) 0% (0 / 31) 14.84% (19 / 128)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/ncp/lib/ncp.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/ncp/lib/ncp.js

Statements: 14.62% (19 / 130)      Branches: 0% (0 / 85)      Functions: 0% (0 / 31)      Lines: 14.84% (19 / 128)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 2411     1   1 1   1                                                       1                                 1                                                             1                                     1                                 1                 1                   1                 1                       1                   1                                     1                 1                   1                                     1                          
var fs = require('fs'),
    path = require('path');
 
const modern = /^v0\.1\d\.\d+$/.test(process.version);
 
module.exports = ncp;
ncp.ncp = ncp;
 
function ncp (source, dest, options, callback) {
  var cback = callback;
 
  if (!callback) {
    cback = options;
    options = {};
  }
 
  var basePath = process.cwd(),
      currentPath = path.resolve(basePath, source),
      targetPath = path.resolve(basePath, dest),
      filter = options.filter,
      rename = options.rename,
      transform = options.transform,
      clobber = options.clobber !== false,
      dereference = options.dereference,
      errs = null,
      eventName = modern ? 'finish' : 'close',
      defer = modern ? setImmediate : process.nextTick,
      started = 0,
      finished = 0,
      running = 0,
      limit = options.limit || ncp.limit || 16;
 
  limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit;
 
  startCopy(currentPath);
  
  function startCopy(source) {
    started++;
    if (filter) {
      if (filter instanceof RegExp) {
        if (!filter.test(source)) {
          return cb(true);
        }
      }
      else if (typeof filter === 'function') {
        if (!filter(source)) {
          return cb(true);
        }
      }
    }
    return getStats(source);
  }
 
  function getStats(source) {
    var stat = dereference ? fs.stat : fs.lstat;
    if (running >= limit) {
      return defer(function () {
        getStats(source);
      });
    }
    running++;
    stat(source, function (err, stats) {
      var item = {};
      if (err) {
        return onError(err);
      }
 
      // We need to get the mode from the stats object and preserve it.
      item.name = source;
      item.mode = stats.mode;
 
      if (stats.isDirectory()) {
        return onDir(item);
      }
      else if (stats.isFile()) {
        return onFile(item);
      }
      else if (stats.isSymbolicLink()) {
        // Symlinks don't really need to know about the mode.
        return onLink(source);
      }
    });
  }
 
  function onFile(file) {
    var target = file.name.replace(currentPath, targetPath);
    if(rename) {
      target =  rename(target);
    }
    isWritable(target, function (writable) {
      if (writable) {
        return copyFile(file, target);
      }
      if(clobber) {
        rmFile(target, function () {
          copyFile(file, target);
        });
      } else {
        return cb();
      }
    });
  }
 
  function copyFile(file, target) {
    var readStream = fs.createReadStream(file.name),
        writeStream = fs.createWriteStream(target, { mode: file.mode });
    
    readStream.on('error', onError);
    writeStream.on('error', onError);
    
    if(transform) {
      transform(readStream, writeStream, file);
    } else {
      writeStream.on('open', function() {
        readStream.pipe(writeStream);
      });
    }
    writeStream.once(eventName, cb);
  }
 
  function rmFile(file, done) {
    fs.unlink(file, function (err) {
      if (err) {
        return onError(err);
      }
      return done();
    });
  }
 
  function onDir(dir) {
    var target = dir.name.replace(currentPath, targetPath);
    isWritable(target, function (writable) {
      if (writable) {
        return mkDir(dir, target);
      }
      copyDir(dir.name);
    });
  }
 
  function mkDir(dir, target) {
    fs.mkdir(target, dir.mode, function (err) {
      if (err) {
        return onError(err);
      }
      copyDir(dir.name);
    });
  }
 
  function copyDir(dir) {
    fs.readdir(dir, function (err, items) {
      if (err) {
        return onError(err);
      }
      items.forEach(function (item) {
        startCopy(dir + '/' + item);
      });
      return cb();
    });
  }
 
  function onLink(link) {
    var target = link.replace(currentPath, targetPath);
    fs.readlink(link, function (err, resolvedPath) {
      if (err) {
        return onError(err);
      }
      checkLink(resolvedPath, target);
    });
  }
 
  function checkLink(resolvedPath, target) {
    isWritable(target, function (writable) {
      if (writable) {
        return makeLink(resolvedPath, target);
      }
      fs.readlink(target, function (err, targetDest) {
        if (err) {
          return onError(err);
        }
        if (targetDest === resolvedPath) {
          return cb();
        }
        return rmFile(target, function () {
          makeLink(resolvedPath, target);
        });
      });
    });
  }
 
  function makeLink(linkPath, target) {
    fs.symlink(linkPath, target, function (err) {
      if (err) {
        return onError(err);
      }
      return cb();
    });
  }
 
  function isWritable(path, done) {
    fs.lstat(path, function (err) {
      if (err) {
        if (err.code === 'ENOENT') return done(true);
        return done(false);
      }
      return done(false);
    });
  }
 
  function onError(err) {
    if (options.stopOnError) {
      return cback(err);
    }
    else if (!errs && options.errs) {
      errs = fs.createWriteStream(options.errs);
    }
    else if (!errs) {
      errs = [];
    }
    if (typeof errs.write === 'undefined') {
      errs.push(err);
    }
    else { 
      errs.write(err.stack + '\n\n');
    }
    return cb();
  }
 
  function cb(skipped) {
    if (!skipped) running--;
    finished++;
    if ((started === finished) && (running === 0)) {
      if (cback !== undefined ) {
        return errs ? cback(errs) : cback(null);
      }
    }
  }
}
 
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/rimraf/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/rimraf/

Statements: 12.67% (19 / 150)      Branches: 0% (0 / 95)      Functions: 0% (0 / 22)      Lines: 12.84% (19 / 148)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/rimraf/
File Statements Branches Functions Lines
rimraf.js 12.67% (19 / 150) 0% (0 / 95) 0% (0 / 22) 12.84% (19 / 148)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/rimraf/rimraf.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/mv/node_modules/rimraf/rimraf.js

Statements: 12.67% (19 / 150)      Branches: 0% (0 / 95)      Functions: 0% (0 / 22)      Lines: 12.84% (19 / 148)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 2501 1   1 1 1     1 1 1   1   1                             1                                                                                                         1                                       1                                           1                                                           1                                       1                                                       1                                       1                                   1                  
module.exports = rimraf
rimraf.sync = rimrafSync
 
var assert = require("assert")
var path = require("path")
var fs = require("fs")
 
// for EMFILE handling
var timeout = 0
exports.EMFILE_MAX = 1000
exports.BUSYTRIES_MAX = 3
 
var isWindows = (process.platform === "win32")
 
function defaults (options) {
  var methods = [
    'unlink',
    'chmod',
    'stat',
    'rmdir',
    'readdir'
  ]
  methods.forEach(function(m) {
    options[m] = options[m] || fs[m]
    m = m + 'Sync'
    options[m] = options[m] || fs[m]
  })
}
 
function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
 
  defaults(options)
 
  if (!cb) throw new Error("No callback passed to rimraf()")
 
  var busyTries = 0
  rimraf_(p, options, function CB (er) {
    if (er) {
      if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
          busyTries < exports.BUSYTRIES_MAX) {
        busyTries ++
        var time = busyTries * 100
        // try again, with the same exact callback as this one.
        return setTimeout(function () {
          rimraf_(p, options, CB)
        }, time)
      }
 
      // this one won't happen if graceful-fs is used.
      if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) {
        return setTimeout(function () {
          rimraf_(p, options, CB)
        }, timeout ++)
      }
 
      // already gone
      if (er.code === "ENOENT") er = null
    }
 
    timeout = 0
    cb(er)
  })
}
 
// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
 
  options.unlink(p, function (er) {
    if (er) {
      if (er.code === "ENOENT")
        return cb(null)
      if (er.code === "EPERM")
        return (isWindows)
          ? fixWinEPERM(p, options, er, cb)
          : rmdir(p, options, er, cb)
      if (er.code === "EISDIR")
        return rmdir(p, options, er, cb)
    }
    return cb(er)
  })
}
 
function fixWinEPERM (p, options, er, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
  if (er)
    assert(er instanceof Error)
 
  options.chmod(p, 666, function (er2) {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er)
    else
      options.stat(p, function(er3, stats) {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er)
        else if (stats.isDirectory())
          rmdir(p, options, er, cb)
        else
          options.unlink(p, cb)
      })
  })
}
 
function fixWinEPERMSync (p, options, er) {
  assert(p)
  assert(options)
  if (er)
    assert(er instanceof Error)
 
  try {
    options.chmodSync(p, 666)
  } catch (er2) {
    if (er2.code === "ENOENT")
      return
    else
      throw er
  }
 
  try {
    var stats = options.statSync(p)
  } catch (er3) {
    if (er3.code === "ENOENT")
      return
    else
      throw er
  }
 
  if (stats.isDirectory())
    rmdirSync(p, options, er)
  else
    options.unlinkSync(p)
}
 
function rmdir (p, options, originalEr, cb) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
  assert(typeof cb === 'function')
 
  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  options.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}
 
function rmkids(p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
 
  options.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return options.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          options.rmdir(p, cb)
      })
    })
  })
}
 
// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
  options = options || {}
  defaults(options)
 
  assert(p)
  assert(options)
 
  try {
    options.unlinkSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "EPERM")
      return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
    if (er.code !== "EISDIR")
      throw er
    rmdirSync(p, options, er)
  }
}
 
function rmdirSync (p, options, originalEr) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
 
  try {
    options.rmdirSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "ENOTDIR")
      throw originalEr
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p, options)
  }
}
 
function rmkidsSync (p, options) {
  assert(p)
  assert(options)
  options.readdirSync(p).forEach(function (f) {
    rimrafSync(path.join(p, f), options)
  })
  options.rmdirSync(p, options)
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/safe-json-stringify/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/safe-json-stringify/

Statements: 23.33% (7 / 30)      Branches: 0% (0 / 14)      Functions: 0% (0 / 6)      Lines: 23.33% (7 / 30)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/safe-json-stringify/
File Statements Branches Functions Lines
index.js 23.33% (7 / 30) 0% (0 / 14) 0% (0 / 6) 23.33% (7 / 30)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/safe-json-stringify/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/bunyan/node_modules/safe-json-stringify/index.js

Statements: 23.33% (7 / 30)      Branches: 0% (0 / 14)      Functions: 0% (0 / 6)      Lines: 23.33% (7 / 30)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 611   1       1                         1     1                                                               1       1    
var hasProp = Object.prototype.hasOwnProperty;
 
function throwsMessage(err) {
	return '[Throws: ' + (err ? err.message : '?') + ']';
}
 
function safeGetValueFromPropertyOnObject(obj, property) {
	if (hasProp.call(obj, property)) {
		try {
			return obj[property];
		}
		catch (err) {
			return throwsMessage(err);
		}
	}
 
	return obj[property];
}
 
function ensureProperties(obj) {
	var seen = [ ]; // store references to objects we have seen before
 
	function visit(obj) {
		if (obj === null || typeof obj !== 'object') {
			return obj;
		}
 
		if (seen.indexOf(obj) !== -1) {
			return '[Circular]';
		}
		seen.push(obj);
 
		if (typeof obj.toJSON === 'function') {
			try {
				return visit(obj.toJSON());
			} catch(err) {
				return throwsMessage(err);
			}
		}
 
		if (Array.isArray(obj)) {
			return obj.map(visit);
		}
 
		return Object.keys(obj).reduce(function(result, prop) {
			// prevent faulty defined getter properties
			result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
			return result;
		}, {});
	};
 
	return visit(obj);
}
 
module.exports = function(data) {
	return JSON.stringify(ensureProperties(data));
}
 
module.exports.ensureProperties = ensureProperties;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/

Statements: 14.42% (15 / 104)      Branches: 0% (0 / 62)      Functions: 0% (0 / 16)      Lines: 14.42% (15 / 104)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/
File Statements Branches Functions Lines
index.js 14.42% (15 / 104) 0% (0 / 62) 0% (0 / 16) 14.42% (15 / 104)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/index.js

Statements: 14.42% (15 / 104)      Branches: 0% (0 / 62)      Functions: 0% (0 / 16)      Lines: 14.42% (15 / 104)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250                            1 1 1 1 1 1 1           1 1                   1                                                                                                                                                                     1             1                                                                                                                                                                                         1                     1             1                      
/*!
 * compression
 * Copyright(c) 2010 Sencha Inc.
 * Copyright(c) 2011 TJ Holowaychuk
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 * @private
 */
 
var accepts = require('accepts')
var bytes = require('bytes')
var compressible = require('compressible')
var debug = require('debug')('compression')
var onHeaders = require('on-headers')
var vary = require('vary')
var zlib = require('zlib')
 
/**
 * Module exports.
 */
 
module.exports = compression
module.exports.filter = shouldCompress
 
/**
 * Compress response data with gzip / deflate.
 *
 * @param {Object} options
 * @return {Function} middleware
 * @public
 */
 
function compression(options) {
  var opts = options || {}
 
  var filter = opts.filter || shouldCompress
  var threshold = typeof opts.threshold === 'string'
    ? bytes(opts.threshold)
    : opts.threshold
 
  if (threshold == null) {
    threshold = 1024
  }
 
  return function compression(req, res, next){
    var compress = true
    var listeners = []
    var write = res.write
    var on = res.on
    var end = res.end
    var stream
 
    // see #8
    req.on('close', function(){
      res.write = res.end = noop
    });
 
    // flush is noop by default
    res.flush = noop;
 
    // proxy
 
    res.write = function(chunk, encoding){
      if (!this._header) {
        // if content-length is set and is lower
        // than the threshold, don't compress
        var len = Number(res.getHeader('Content-Length'))
        checkthreshold(len)
        this._implicitHeader();
      }
      return stream
        ? stream.write(new Buffer(chunk, encoding))
        : write.call(res, chunk, encoding);
    };
 
    res.end = function(chunk, encoding){
      var len
 
      if (chunk) {
        len = Buffer.isBuffer(chunk)
          ? chunk.length
          : Buffer.byteLength(chunk, encoding)
      }
 
      if (!this._header) {
        len = Number(this.getHeader('Content-Length')) || len
        checkthreshold(len)
        this._implicitHeader()
      }
 
      if (!stream) {
        return end.call(res, chunk, encoding)
      }
 
      // write Buffer for Node.js 0.8
      return chunk
        ? stream.end(new Buffer(chunk, encoding))
        : stream.end()
    };
 
    res.on = function(type, listener){
      if (!listeners || type !== 'drain') {
        return on.call(this, type, listener)
      }
 
      if (stream) {
        return stream.on(type, listener)
      }
 
      // buffer listeners for future stream
      listeners.push([type, listener])
 
      return this
    }
 
    function checkthreshold(len) {
      if (compress && len < threshold) {
        debug('size below threshold')
        compress = false
      }
    }
 
    function nocompress(msg) {
      debug('no compression' + (msg ? ': ' + msg : ''))
      addListeners(res, on, listeners)
      listeners = null
    }
 
    onHeaders(res, function(){
      // determine if request is filtered
      if (!filter(req, res)) {
        nocompress('filtered')
        return
      }
 
      // vary
      vary(res, 'Accept-Encoding')
 
      if (!compress) {
        nocompress()
        return
      }
 
      var encoding = res.getHeader('Content-Encoding') || 'identity';
 
      // already encoded
      if ('identity' !== encoding) {
        nocompress('already encoded')
        return
      }
 
      // head
      if ('HEAD' === req.method) {
        nocompress('HEAD request')
        return
      }
 
      // compression method
      var accept = accepts(req)
      var method = accept.encoding(['gzip', 'deflate', 'identity'])
 
      // we really don't prefer deflate
      if (method === 'deflate' && accept.encoding(['gzip'])) {
        method = accept.encoding(['gzip', 'identity'])
      }
 
      // negotiation failed
      if (!method || method === 'identity') {
        nocompress('not acceptable')
        return
      }
 
      // compression stream
      debug('%s compression', method)
      stream = method === 'gzip'
        ? zlib.createGzip(opts)
        : zlib.createDeflate(opts)
 
      // add bufferred listeners to stream
      addListeners(stream, stream.on, listeners)
 
      // overwrite the flush method
      res.flush = function(){
        stream.flush();
      }
 
      // header fields
      res.setHeader('Content-Encoding', method);
      res.removeHeader('Content-Length');
 
      // compression
      stream.on('data', function(chunk){
        if (write.call(res, chunk) === false) {
          stream.pause()
        }
      });
 
      stream.on('end', function(){
        end.call(res);
      });
 
      on.call(res, 'drain', function() {
        stream.resume()
      });
    });
 
    next();
  };
}
 
/**
 * Add bufferred listeners to stream
 * @private
 */
 
function addListeners(stream, on, listeners) {
  for (var i = 0; i < listeners.length; i++) {
    on.apply(stream, listeners[i])
  }
}
 
/**
 * No-operation function
 * @private
 */
 
function noop(){}
 
/**
 * Default filter function.
 * @private
 */
 
function shouldCompress(req, res) {
  var type = res.getHeader('Content-Type')
 
  if (type === undefined || !compressible(type)) {
    debug('%s not compressible', type)
    return false
  }
 
  return true
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/

Statements: 20.37% (11 / 54)      Branches: 0% (0 / 34)      Functions: 0% (0 / 7)      Lines: 26.83% (11 / 41)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/
File Statements Branches Functions Lines
index.js 20.37% (11 / 54) 0% (0 / 34) 0% (0 / 7) 26.83% (11 / 41)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/index.js

Statements: 20.37% (11 / 54)      Branches: 0% (0 / 34)      Functions: 0% (0 / 7)      Lines: 26.83% (11 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 1621 1   1   1   1                                                                                                 1                                                   1                                         1                                           1                                     1                         1        
var Negotiator = require('negotiator')
var mime = require('mime-types')
 
var slice = [].slice
 
module.exports = Accepts
 
function Accepts(req) {
  if (!(this instanceof Accepts))
    return new Accepts(req)
 
  this.headers = req.headers
  this.negotiator = Negotiator(req)
}
 
/**
 * Check if the given `type(s)` is acceptable, returning
 * the best match when true, otherwise `undefined`, in which
 * case you should respond with 406 "Not Acceptable".
 *
 * The `type` value may be a single mime type string
 * such as "application/json", the extension name
 * such as "json" or an array `["json", "html", "text/plain"]`. When a list
 * or array is given the _best_ match, if any is returned.
 *
 * Examples:
 *
 *     // Accept: text/html
 *     this.types('html');
 *     // => "html"
 *
 *     // Accept: text/*, application/json
 *     this.types('html');
 *     // => "html"
 *     this.types('text/html');
 *     // => "text/html"
 *     this.types('json', 'text');
 *     // => "json"
 *     this.types('application/json');
 *     // => "application/json"
 *
 *     // Accept: text/*, application/json
 *     this.types('image/png');
 *     this.types('png');
 *     // => undefined
 *
 *     // Accept: text/*;q=.5, application/json
 *     this.types(['html', 'json']);
 *     this.types('html', 'json');
 *     // => "json"
 *
 * @param {String|Array} type(s)...
 * @return {String|Array|Boolean}
 * @api public
 */
 
Accepts.prototype.type =
Accepts.prototype.types = function (types) {
  if (!Array.isArray(types)) types = slice.call(arguments);
  var n = this.negotiator;
  if (!types.length) return n.mediaTypes();
  if (!this.headers.accept) return types[0];
  var mimes = types.map(extToMime);
  var accepts = n.mediaTypes(mimes.filter(validMime));
  var first = accepts[0];
  if (!first) return false;
  return types[mimes.indexOf(first)];
}
 
/**
 * Return accepted encodings or best fit based on `encodings`.
 *
 * Given `Accept-Encoding: gzip, deflate`
 * an array sorted by quality is returned:
 *
 *     ['gzip', 'deflate']
 *
 * @param {String|Array} encoding(s)...
 * @return {String|Array}
 * @api public
 */
 
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings) {
  if (!Array.isArray(encodings)) encodings = slice.call(arguments);
  var n = this.negotiator;
  if (!encodings.length) return n.encodings();
  return n.encodings(encodings)[0] || false;
}
 
/**
 * Return accepted charsets or best fit based on `charsets`.
 *
 * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
 * an array sorted by quality is returned:
 *
 *     ['utf-8', 'utf-7', 'iso-8859-1']
 *
 * @param {String|Array} charset(s)...
 * @return {String|Array}
 * @api public
 */
 
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets) {
  if (!Array.isArray(charsets)) charsets = [].slice.call(arguments);
  var n = this.negotiator;
  if (!charsets.length) return n.charsets();
  if (!this.headers['accept-charset']) return charsets[0];
  return n.charsets(charsets)[0] || false;
}
 
/**
 * Return accepted languages or best fit based on `langs`.
 *
 * Given `Accept-Language: en;q=0.8, es, pt`
 * an array sorted by quality is returned:
 *
 *     ['es', 'pt', 'en']
 *
 * @param {String|Array} lang(s)...
 * @return {Array|String}
 * @api public
 */
 
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (langs) {
  if (!Array.isArray(langs)) langs = slice.call(arguments);
  var n = this.negotiator;
  if (!langs.length) return n.languages();
  if (!this.headers['accept-language']) return langs[0];
  return n.languages(langs)[0] || false;
}
 
/**
 * Convert extnames to mime.
 *
 * @param {String} type
 * @return {String}
 * @api private
 */
 
function extToMime(type) {
  if (~type.indexOf('/')) return type;
  return mime.lookup(type);
}
 
/**
 * Check if mime is valid.
 *
 * @param {String} type
 * @return {String}
 * @api private
 */
 
function validMime(type) {
  return typeof type === 'string';
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/
File Statements Branches Functions Lines
index.js 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/index.js

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  1     1   1   1 1799 1799 1799 789 789 1018       1               1                     1                     1         1                      
 
var db = require('mime-db')
 
// types[extension] = type
exports.types = Object.create(null)
// extensions[type] = [extensions]
exports.extensions = Object.create(null)
 
Object.keys(db).forEach(function (name) {
  var mime = db[name]
  var exts = mime.extensions
  if (!exts || !exts.length) return
  exports.extensions[name] = exts
  exts.forEach(function (ext) {
    exports.types[ext] = name
  })
})
 
exports.lookup = function (string) {
  if (!string || typeof string !== "string") return false
  // remove any leading paths, though we should just use path.basename
  string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
  if (!string) return false
  return exports.types[string] || false
}
 
exports.extension = function (type) {
  if (!type || typeof type !== "string") return false
  // to do: use media-typer
  type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
  if (!type) return false
  var exts = exports.extensions[type[1].toLowerCase()]
  if (!exts || !exts.length) return false
  return exts[0]
}
 
// type has to be an exact mime type
exports.charset = function (type) {
  var mime = db[type]
  if (mime && mime.charset) return mime.charset
 
  // default text/* to utf-8
  if (/^text\//.test(type)) return 'UTF-8'
 
  return false
}
 
// backwards compatibility
exports.charsets = {
  lookup: exports.charset
}
 
// to do: maybe use set-type module or something
exports.contentType = function (type) {
  if (!type || typeof type !== "string") return false
  if (!~type.indexOf('/')) type = exports.lookup(type)
  if (!type) return false
  if (!~type.indexOf('charset')) {
    var charset = exports.charset(type)
    if (charset) type += '; charset=' + charset.toLowerCase()
  }
  return type
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13                    1    
/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = require('./db.json')
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/

Statements: 60.53% (23 / 38)      Branches: 0% (0 / 10)      Functions: 0% (0 / 9)      Lines: 60.53% (23 / 38)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/
File Statements Branches Functions Lines
index.js 60.53% (23 / 38) 0% (0 / 10) 0% (0 / 9) 60.53% (23 / 38)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/index.js

Statements: 60.53% (23 / 38)      Branches: 0% (0 / 10)      Functions: 0% (0 / 9)      Lines: 60.53% (23 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64  1 1 1 1   1 1   1               1         1       1         1       1         1       1         1         1 1 1 1 1 1 1 1    
 
var preferredCharsets = require('./lib/charset');
var preferredEncodings = require('./lib/encoding');
var preferredLanguages = require('./lib/language');
var preferredMediaTypes = require('./lib/mediaType');
 
module.exports = Negotiator;
Negotiator.Negotiator = Negotiator;
 
function Negotiator(request) {
  if (!(this instanceof Negotiator)) {
    return new Negotiator(request);
  }
 
  this.request = request;
}
 
Negotiator.prototype.charset = function charset(available) {
  var set = this.charsets(available);
  return set && set[0];
};
 
Negotiator.prototype.charsets = function charsets(available) {
  return preferredCharsets(this.request.headers['accept-charset'], available);
};
 
Negotiator.prototype.encoding = function encoding(available) {
  var set = this.encodings(available);
  return set && set[0];
};
 
Negotiator.prototype.encodings = function encodings(available) {
  return preferredEncodings(this.request.headers['accept-encoding'], available);
};
 
Negotiator.prototype.language = function language(available) {
  var set = this.languages(available);
  return set && set[0];
};
 
Negotiator.prototype.languages = function languages(available) {
  return preferredLanguages(this.request.headers['accept-language'], available);
};
 
Negotiator.prototype.mediaType = function mediaType(available) {
  var set = this.mediaTypes(available);
  return set && set[0];
};
 
Negotiator.prototype.mediaTypes = function mediaTypes(available) {
  return preferredMediaTypes(this.request.headers.accept, available);
};
 
// Backwards compatibility
Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/

Statements: 15.32% (38 / 248)      Branches: 0% (0 / 155)      Functions: 0% (0 / 45)      Lines: 15.77% (38 / 241)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/
File Statements Branches Functions Lines
charset.js 17.65% (9 / 51) 0% (0 / 30) 0% (0 / 10) 18% (9 / 50)
encoding.js 15.79% (9 / 57) 0% (0 / 34) 0% (0 / 10) 16.07% (9 / 56)
language.js 15.25% (9 / 59) 0% (0 / 38) 0% (0 / 10) 16.36% (9 / 55)
mediaType.js 13.58% (11 / 81) 0% (0 / 53) 0% (0 / 15) 13.75% (11 / 80)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/charset.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/charset.js

Statements: 17.65% (9 / 51)      Branches: 0% (0 / 30)      Functions: 0% (0 / 10)      Lines: 18% (9 / 50)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 1041 1   1                                 1                                               1                           1                               1                                         1       1        
module.exports = preferredCharsets;
preferredCharsets.preferredCharsets = preferredCharsets;
 
function parseAcceptCharset(accept) {
  var accepts = accept.split(',');
 
  for (var i = 0, j = 0; i < accepts.length; i++) {
    var charset = parseCharset(accepts[i].trim(), i);
 
    if (charset) {
      accepts[j++] = charset;
    }
  }
 
  // trim accepts
  accepts.length = j;
 
  return accepts;
}
 
function parseCharset(s, i) {
  var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
  if (!match) return null;
 
  var charset = match[1];
  var q = 1;
  if (match[2]) {
    var params = match[2].split(';')
    for (var i = 0; i < params.length; i ++) {
      var p = params[i].trim().split('=');
      if (p[0] === 'q') {
        q = parseFloat(p[1]);
        break;
      }
    }
  }
 
  return {
    charset: charset,
    q: q,
    i: i
  };
}
 
function getCharsetPriority(charset, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};
 
  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(charset, accepted[i], index);
 
    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }
 
  return priority;
}
 
function specify(charset, spec, index) {
  var s = 0;
  if(spec.charset.toLowerCase() === charset.toLowerCase()){
    s |= 1;
  } else if (spec.charset !== '*' ) {
    return null
  }
 
  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s
  }
}
 
function preferredCharsets(accept, provided) {
  // RFC 2616 sec 14.2: no header = *
  var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');
 
  if (!provided) {
    // sorted list of all charsets
    return accepts.filter(isQuality).sort(compareSpecs).map(function getCharset(spec) {
      return spec.charset;
    });
  }
 
  var priorities = provided.map(function getPriority(type, index) {
    return getCharsetPriority(type, accepts, index);
  });
 
  // sorted list of accepted charsets
  return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
    return provided[priorities.indexOf(priority)];
  });
}
 
function compareSpecs(a, b) {
  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
}
 
function isQuality(spec) {
  return spec.q > 0;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/encoding.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/encoding.js

Statements: 15.79% (9 / 57)      Branches: 0% (0 / 34)      Functions: 0% (0 / 10)      Lines: 16.07% (9 / 56)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 1201 1   1                                                                 1                                                 1                           1                               1                                       1       1        
module.exports = preferredEncodings;
preferredEncodings.preferredEncodings = preferredEncodings;
 
function parseAcceptEncoding(accept) {
  var accepts = accept.split(',');
  var hasIdentity = false;
  var minQuality = 1;
 
  for (var i = 0, j = 0; i < accepts.length; i++) {
    var encoding = parseEncoding(accepts[i].trim(), i);
 
    if (encoding) {
      accepts[j++] = encoding;
      hasIdentity = hasIdentity || specify('identity', encoding);
      minQuality = Math.min(minQuality, encoding.q || 1);
    }
  }
 
  if (!hasIdentity) {
    /*
     * If identity doesn't explicitly appear in the accept-encoding header,
     * it's added to the list of acceptable encoding with the lowest q
     */
    accepts[j++] = {
      encoding: 'identity',
      q: minQuality,
      i: i
    };
  }
 
  // trim accepts
  accepts.length = j;
 
  return accepts;
}
 
function parseEncoding(s, i) {
  var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
 
  if (!match) return null;
 
  var encoding = match[1];
  var q = 1;
  if (match[2]) {
    var params = match[2].split(';');
    for (var i = 0; i < params.length; i ++) {
      var p = params[i].trim().split('=');
      if (p[0] === 'q') {
        q = parseFloat(p[1]);
        break;
      }
    }
  }
 
  return {
    encoding: encoding,
    q: q,
    i: i
  };
}
 
function getEncodingPriority(encoding, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};
 
  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(encoding, accepted[i], index);
 
    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }
 
  return priority;
}
 
function specify(encoding, spec, index) {
  var s = 0;
  if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
    s |= 1;
  } else if (spec.encoding !== '*' ) {
    return null
  }
 
  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s
  }
};
 
function preferredEncodings(accept, provided) {
  var accepts = parseAcceptEncoding(accept || '');
 
  if (!provided) {
    // sorted list of all encodings
    return accepts.filter(isQuality).sort(compareSpecs).map(function getEncoding(spec) {
      return spec.encoding;
    });
  }
 
  var priorities = provided.map(function getPriority(type, index) {
    return getEncodingPriority(type, accepts, index);
  });
 
  // sorted list of accepted encodings
  return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) {
    return provided[priorities.indexOf(priority)];
  });
}
 
function compareSpecs(a, b) {
  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
}
 
function isQuality(spec) {
  return spec.q > 0;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/language.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/language.js

Statements: 15.25% (9 / 59)      Branches: 0% (0 / 38)      Functions: 0% (0 / 10)      Lines: 16.36% (9 / 55)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 1141 1   1                                 1                                                       1                           1                                           1                                         1       1        
module.exports = preferredLanguages;
preferredLanguages.preferredLanguages = preferredLanguages;
 
function parseAcceptLanguage(accept) {
  var accepts = accept.split(',');
 
  for (var i = 0, j = 0; i < accepts.length; i++) {
    var langauge = parseLanguage(accepts[i].trim(), i);
 
    if (langauge) {
      accepts[j++] = langauge;
    }
  }
 
  // trim accepts
  accepts.length = j;
 
  return accepts;
}
 
function parseLanguage(s, i) {
  var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/);
  if (!match) return null;
 
  var prefix = match[1],
      suffix = match[2],
      full = prefix;
 
  if (suffix) full += "-" + suffix;
 
  var q = 1;
  if (match[3]) {
    var params = match[3].split(';')
    for (var i = 0; i < params.length; i ++) {
      var p = params[i].split('=');
      if (p[0] === 'q') q = parseFloat(p[1]);
    }
  }
 
  return {
    prefix: prefix,
    suffix: suffix,
    q: q,
    i: i,
    full: full
  };
}
 
function getLanguagePriority(language, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};
 
  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(language, accepted[i], index);
 
    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }
 
  return priority;
}
 
function specify(language, spec, index) {
  var p = parseLanguage(language)
  if (!p) return null;
  var s = 0;
  if(spec.full.toLowerCase() === p.full.toLowerCase()){
    s |= 4;
  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
    s |= 2;
  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
    s |= 1;
  } else if (spec.full !== '*' ) {
    return null
  }
 
  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s
  }
};
 
function preferredLanguages(accept, provided) {
  // RFC 2616 sec 14.4: no header = *
  var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');
 
  if (!provided) {
    // sorted list of all languages
    return accepts.filter(isQuality).sort(compareSpecs).map(function getLanguage(spec) {
      return spec.full;
    });
  }
 
  var priorities = provided.map(function getPriority(type, index) {
    return getLanguagePriority(type, accepts, index);
  });
 
  // sorted list of accepted languages
  return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
    return provided[priorities.indexOf(priority)];
  });
}
 
function compareSpecs(a, b) {
  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
}
 
function isQuality(spec) {
  return spec.q > 0;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/mediaType.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/accepts/node_modules/negotiator/lib/mediaType.js

Statements: 13.58% (11 / 81)      Branches: 0% (0 / 53)      Functions: 0% (0 / 15)      Lines: 13.75% (11 / 80)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181                1 1   1                                 1                                                                               1                           1                                                                               1                                         1       1       1                       1                                  
/**
 * negotiator
 * Copyright(c) 2012 Isaac Z. Schlueter
 * Copyright(c) 2014 Federico Romero
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */
 
module.exports = preferredMediaTypes;
preferredMediaTypes.preferredMediaTypes = preferredMediaTypes;
 
function parseAccept(accept) {
  var accepts = splitMediaTypes(accept);
 
  for (var i = 0, j = 0; i < accepts.length; i++) {
    var mediaType = parseMediaType(accepts[i].trim(), i);
 
    if (mediaType) {
      accepts[j++] = mediaType;
    }
  }
 
  // trim accepts
  accepts.length = j;
 
  return accepts;
};
 
function parseMediaType(s, i) {
  var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/);
  if (!match) return null;
 
  var type = match[1],
      subtype = match[2],
      full = "" + type + "/" + subtype,
      params = {},
      q = 1;
 
  if (match[3]) {
    params = match[3].split(';').map(function(s) {
      return s.trim().split('=');
    }).reduce(function (set, p) {
      var name = p[0].toLowerCase();
      var value = p[1];
 
      set[name] = value && value[0] === '"' && value[value.length - 1] === '"'
        ? value.substr(1, value.length - 2)
        : value;
 
      return set;
    }, params);
 
    if (params.q != null) {
      q = parseFloat(params.q);
      delete params.q;
    }
  }
 
  return {
    type: type,
    subtype: subtype,
    params: params,
    q: q,
    i: i,
    full: full
  };
}
 
function getMediaTypePriority(type, accepted, index) {
  var priority = {o: -1, q: 0, s: 0};
 
  for (var i = 0; i < accepted.length; i++) {
    var spec = specify(type, accepted[i], index);
 
    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
      priority = spec;
    }
  }
 
  return priority;
}
 
function specify(type, spec, index) {
  var p = parseMediaType(type);
  var s = 0;
 
  if (!p) {
    return null;
  }
 
  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
    s |= 4
  } else if(spec.type != '*') {
    return null;
  }
 
  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
    s |= 2
  } else if(spec.subtype != '*') {
    return null;
  }
 
  var keys = Object.keys(spec.params);
  if (keys.length > 0) {
    if (keys.every(function (k) {
      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
    })) {
      s |= 1
    } else {
      return null
    }
  }
 
  return {
    i: index,
    o: spec.i,
    q: spec.q,
    s: s,
  }
 
}
 
function preferredMediaTypes(accept, provided) {
  // RFC 2616 sec 14.2: no header = */*
  var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');
 
  if (!provided) {
    // sorted list of all types
    return accepts.filter(isQuality).sort(compareSpecs).map(function getType(spec) {
      return spec.full;
    });
  }
 
  var priorities = provided.map(function getPriority(type, index) {
    return getMediaTypePriority(type, accepts, index);
  });
 
  // sorted list of accepted types
  return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
    return provided[priorities.indexOf(priority)];
  });
}
 
function compareSpecs(a, b) {
  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
}
 
function isQuality(spec) {
  return spec.q > 0;
}
 
function quoteCount(string) {
  var count = 0;
  var index = 0;
 
  while ((index = string.indexOf('"', index)) !== -1) {
    count++;
    index++;
  }
 
  return count;
}
 
function splitMediaTypes(accept) {
  var accepts = accept.split(',');
 
  for (var i = 1, j = 0; i < accepts.length; i++) {
    if (quoteCount(accepts[j]) % 2 == 0) {
      accepts[++j] = accepts[i];
    } else {
      accepts[j] += ',' + accepts[i];
    }
  }
 
  // trim accepts
  accepts.length = j + 1;
 
  return accepts;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/bytes/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/bytes/

Statements: 11.76% (2 / 17)      Branches: 0% (0 / 10)      Functions: 0% (0 / 2)      Lines: 16.67% (2 / 12)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/bytes/
File Statements Branches Functions Lines
index.js 11.76% (2 / 17) 0% (0 / 10) 0% (0 / 2) 16.67% (2 / 12)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/bytes/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/bytes/index.js

Statements: 11.76% (2 / 17)      Branches: 0% (0 / 10)      Functions: 0% (0 / 2)      Lines: 16.67% (2 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                  1                                               1                  
 
/**
 * Parse byte `size` string.
 *
 * @param {String} size
 * @return {Number}
 * @api public
 */
 
module.exports = function(size) {
  if ('number' == typeof size) return convert(size);
  var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb|tb)$/)
    , n = parseFloat(parts[1])
    , type = parts[2];
 
  var map = {
      kb: 1 << 10
    , mb: 1 << 20
    , gb: 1 << 30
    , tb: ((1 << 30) * 1024)
  };
 
  return map[type] * n;
};
 
/**
 * convert bytes into string.
 *
 * @param {Number} b - bytes to convert
 * @return {String}
 * @api public
 */
 
function convert (b) {
  var tb = ((1 << 30) * 1024), gb = 1 << 30, mb = 1 << 20, kb = 1 << 10, abs = Math.abs(b);
  if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb';
  if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
  if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
  if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';
  return b + 'b';
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/

Statements: 27.27% (3 / 11)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 33.33% (3 / 9)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/
File Statements Branches Functions Lines
index.js 27.27% (3 / 11) 0% (0 / 8) 0% (0 / 1) 33.33% (3 / 9)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/index.js

Statements: 27.27% (3 / 11)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 33.33% (3 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41                    1           1                 1                              
/*!
 * compressible
 * Copyright(c) 2014 Jeremiah Senkpiel
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 */
 
var db = require('mime-db')
 
/**
 * Module exports.
 */
 
module.exports = compressible
 
/**
 * Checks if a type is compressible.
 *
 * @param {string} type
 * @return {Boolean} compressible
 */
 
function compressible(type) {
  if (!type || typeof type !== "string") return false
 
  // Strip charset
  var i = type.indexOf(';')
  if (~i) type = type.slice(0, i)
 
  // handle types that have capitals or excess space
  type = type.trim().toLowerCase()
  
  // attempt to look up from database; fallback to regex if not found
  var mime = db[type]
  return mime ? mime.compressible : /^text\/|\+json$|\+text$|\+xml$/.test(type)
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/node_modules/mime-db/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/node_modules/mime-db/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/node_modules/mime-db/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/node_modules/mime-db/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/compressible/node_modules/mime-db/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13                    1    
/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = require('./db.json')
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/

Statements: 40.14% (57 / 142)      Branches: 14.71% (10 / 68)      Functions: 27.78% (5 / 18)      Lines: 40.88% (56 / 137)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/
File Statements Branches Functions Lines
debug.js 43.59% (34 / 78) 11.43% (4 / 35) 33.33% (3 / 9) 45.21% (33 / 73)
node.js 35.94% (23 / 64) 18.18% (6 / 33) 22.22% (2 / 9) 35.94% (23 / 64)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/debug.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/debug.js

Statements: 43.59% (34 / 78)      Branches: 11.43% (4 / 35)      Functions: 33.33% (3 / 9)      Lines: 45.21% (33 / 73)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199                1 1 1 1 1 1           1 1               1           1           1                 1                       1     1   1     1                                                                                                 1   1   1   1                     1 1   1 1   1 1                               1                       1 1 1         1         1                     1          
 
/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 *
 * Expose `debug()` as the module.
 */
 
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
 
/**
 * The currently active debug mode names, and names to skip.
 */
 
exports.names = [];
exports.skips = [];
 
/**
 * Map of special "%n" handling functions, for the debug "format" argument.
 *
 * Valid key names are a single, lowercased letter, i.e. "n".
 */
 
exports.formatters = {};
 
/**
 * Previously assigned color.
 */
 
var prevColor = 0;
 
/**
 * Previous log timestamp.
 */
 
var prevTime;
 
/**
 * Select a color.
 *
 * @return {Number}
 * @api private
 */
 
function selectColor() {
  return exports.colors[prevColor++ % exports.colors.length];
}
 
/**
 * Create a debugger with the given `namespace`.
 *
 * @param {String} namespace
 * @return {Function}
 * @api public
 */
 
function debug(namespace) {
 
  // define the `disabled` version
  function disabled() {
  }
  disabled.enabled = false;
 
  // define the `enabled` version
  function enabled() {
 
    var self = enabled;
 
    // set `diff` timestamp
    var curr = +new Date();
    var ms = curr - (prevTime || curr);
    self.diff = ms;
    self.prev = prevTime;
    self.curr = curr;
    prevTime = curr;
 
    // add the `color` if not set
    if (null == self.useColors) self.useColors = exports.useColors();
    if (null == self.color && self.useColors) self.color = selectColor();
 
    var args = Array.prototype.slice.call(arguments);
 
    args[0] = exports.coerce(args[0]);
 
    if ('string' !== typeof args[0]) {
      // anything else let's inspect with %o
      args = ['%o'].concat(args);
    }
 
    // apply any `formatters` transformations
    var index = 0;
    args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
      // if we encounter an escaped % then don't increase the array index
      if (match === '%%') return match;
      index++;
      var formatter = exports.formatters[format];
      if ('function' === typeof formatter) {
        var val = args[index];
        match = formatter.call(self, val);
 
        // now we need to remove `args[index]` since it's inlined in the `format`
        args.splice(index, 1);
        index--;
      }
      return match;
    });
 
    if ('function' === typeof exports.formatArgs) {
      args = exports.formatArgs.apply(self, args);
    }
    var logFn = enabled.log || exports.log || console.log.bind(console);
    logFn.apply(self, args);
  }
  enabled.enabled = true;
 
  var fn = exports.enabled(namespace) ? enabled : disabled;
 
  fn.namespace = namespace;
 
  return fn;
}
 
/**
 * Enables a debug mode by namespaces. This can include modes
 * separated by a colon and wildcards.
 *
 * @param {String} namespaces
 * @api public
 */
 
function enable(namespaces) {
  exports.save(namespaces);
 
  var split = (namespaces || '').split(/[\s,]+/);
  var len = split.length;
 
  for (var i = 0; i < len; i++) {
    Eif (!split[i]) continue; // ignore empty strings
    namespaces = split[i].replace(/\*/g, '.*?');
    if (namespaces[0] === '-') {
      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
    } else {
      exports.names.push(new RegExp('^' + namespaces + '$'));
    }
  }
}
 
/**
 * Disable debug output.
 *
 * @api public
 */
 
function disable() {
  exports.enable('');
}
 
/**
 * Returns true if the given mode name is enabled, false otherwise.
 *
 * @param {String} name
 * @return {Boolean}
 * @api public
 */
 
function enabled(name) {
  var i, len;
  for (i = 0, len = exports.skips.length; i < len; i++) {
    if (exports.skips[i].test(name)) {
      return false;
    }
  }
  for (i = 0, len = exports.names.length; i < len; i++) {
    if (exports.names[i].test(name)) {
      return true;
    }
  }
  return false;
}
 
/**
 * Coerce `val`.
 *
 * @param {Mixed} val
 * @return {Mixed}
 * @api private
 */
 
function coerce(val) {
  if (val instanceof Error) return val.stack || val.message;
  return val;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node.js

Statements: 35.94% (23 / 64)      Branches: 18.18% (6 / 33)      Functions: 22.22% (2 / 9)      Lines: 35.94% (23 / 64)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211          1 1               1 1 1 1 1 1           1                 1 1               1                               1                     1                     1                                             1                     1 1     1                         1 1                   1                                                                                                                                 1    
 
/**
 * Module dependencies.
 */
 
var tty = require('tty');
var util = require('util');
 
/**
 * This is the Node.js implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */
 
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
 
/**
 * Colors.
 */
 
exports.colors = [6, 2, 3, 4, 5, 1];
 
/**
 * The file descriptor to write the `debug()` calls to.
 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
 *
 *   $ DEBUG_FD=3 node script.js 3>debug.log
 */
 
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
var stream = 1 === fd ? process.stdout :
             2 === fd ? process.stderr :
             createWritableStdioStream(fd);
 
/**
 * Is stdout a TTY? Colored output is enabled when `true`.
 */
 
function useColors() {
  var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase();
  if (0 === debugColors.length) {
    return tty.isatty(fd);
  } else {
    return '0' !== debugColors
        && 'no' !== debugColors
        && 'false' !== debugColors
        && 'disabled' !== debugColors;
  }
}
 
/**
 * Map %o to `util.inspect()`, since Node doesn't do that out of the box.
 */
 
var inspect = (4 === util.inspect.length ?
  // node <= 0.8.x
  function (v, colors) {
    return util.inspect(v, void 0, void 0, colors);
  } :
  // node > 0.8.x
  function (v, colors) {
    return util.inspect(v, { colors: colors });
  }
);
 
exports.formatters.o = function(v) {
  return inspect(v, this.useColors)
    .replace(/\s*\n\s*/g, ' ');
};
 
/**
 * Adds ANSI color escape codes if enabled.
 *
 * @api public
 */
 
function formatArgs() {
  var args = arguments;
  var useColors = this.useColors;
  var name = this.namespace;
 
  if (useColors) {
    var c = this.color;
 
    args[0] = '  \u001b[3' + c + ';1m' + name + ' '
      + '\u001b[0m'
      + args[0] + '\u001b[3' + c + 'm'
      + ' +' + exports.humanize(this.diff) + '\u001b[0m';
  } else {
    args[0] = new Date().toUTCString()
      + ' ' + name + ' ' + args[0];
  }
  return args;
}
 
/**
 * Invokes `console.error()` with the specified arguments.
 */
 
function log() {
  return stream.write(util.format.apply(this, arguments) + '\n');
}
 
/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */
 
function save(namespaces) {
  Eif (null == namespaces) {
    // If you set a process.env field to null or undefined, it gets cast to the
    // string 'null' or 'undefined'. Just delete instead.
    delete process.env.DEBUG;
  } else {
    process.env.DEBUG = namespaces;
  }
}
 
/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */
 
function load() {
  return process.env.DEBUG;
}
 
/**
 * Copied from `node/src/node.js`.
 *
 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
 */
 
function createWritableStdioStream (fd) {
  var stream;
  var tty_wrap = process.binding('tty_wrap');
 
  // Note stream._type is used for test-module-load-list.js
 
  switch (tty_wrap.guessHandleType(fd)) {
    case 'TTY':
      stream = new tty.WriteStream(fd);
      stream._type = 'tty';
 
      // Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;
 
    case 'FILE':
      var fs = require('fs');
      stream = new fs.SyncWriteStream(fd, { autoClose: false });
      stream._type = 'fs';
      break;
 
    case 'PIPE':
    case 'TCP':
      var net = require('net');
      stream = new net.Socket({
        fd: fd,
        readable: false,
        writable: true
      });
 
      // FIXME Should probably have an option in net.Socket to create a
      // stream from an existing fd which is writable only. But for now
      // we'll just add this hack and set the `readable` member to false.
      // Test: ./node test/fixtures/echo.js < /etc/passwd
      stream.readable = false;
      stream.read = null;
      stream._type = 'pipe';
 
      // FIXME Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;
 
    default:
      // Probably an error on in uv_guess_handle()
      throw new Error('Implement me. Unknown stream file type!');
  }
 
  // For supporting legacy API we put the FD here.
  stream.fd = fd;
 
  stream._isStdio = true;
 
  return stream;
}
 
/**
 * Enable namespaces listed in `process.env.DEBUG` initially.
 */
 
exports.enable(load());
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node_modules/ms/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node_modules/ms/

Statements: 22.73% (10 / 44)      Branches: 0% (0 / 57)      Functions: 0% (0 / 5)      Lines: 28.57% (10 / 35)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node_modules/ms/
File Statements Branches Functions Lines
index.js 22.73% (10 / 44) 0% (0 / 57) 0% (0 / 5) 28.57% (10 / 35)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node_modules/ms/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/debug/node_modules/ms/index.js

Statements: 22.73% (10 / 44)      Branches: 0% (0 / 57)      Functions: 0% (0 / 5)      Lines: 28.57% (10 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127        1 1 1 1 1                             1                               1                                                                                                         1                               1                       1            
/**
 * Helpers.
 */
 
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
 
/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} options
 * @return {String|Number}
 * @api public
 */
 
module.exports = function(val, options){
  options = options || {};
  if ('string' == typeof val) return parse(val);
  return options.long
    ? long(val)
    : short(val);
};
 
/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */
 
function parse(str) {
  str = '' + str;
  if (str.length > 10000) return;
  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  if (!match) return;
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
  }
}
 
/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function short(ms) {
  if (ms >= d) return Math.round(ms / d) + 'd';
  if (ms >= h) return Math.round(ms / h) + 'h';
  if (ms >= m) return Math.round(ms / m) + 'm';
  if (ms >= s) return Math.round(ms / s) + 's';
  return ms + 'ms';
}
 
/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function long(ms) {
  return plural(ms, d, 'day')
    || plural(ms, h, 'hour')
    || plural(ms, m, 'minute')
    || plural(ms, s, 'second')
    || ms + ' ms';
}
 
/**
 * Pluralization helper.
 */
 
function plural(ms, n, name) {
  if (ms < n) return;
  if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  return Math.ceil(ms / n) + ' ' + name + 's';
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/on-headers/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/on-headers/

Statements: 11.11% (4 / 36)      Branches: 0% (0 / 22)      Functions: 0% (0 / 4)      Lines: 11.43% (4 / 35)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/on-headers/
File Statements Branches Functions Lines
index.js 11.11% (4 / 36) 0% (0 / 22) 0% (0 / 4) 11.43% (4 / 35)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/on-headers/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/on-headers/index.js

Statements: 11.11% (4 / 36)      Branches: 0% (0 / 22)      Functions: 0% (0 / 4)      Lines: 11.43% (4 / 35)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93                    1                   1                       1                                               1                                                                        
/*!
 * on-headers
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Reference to Array slice.
 */
 
var slice = Array.prototype.slice
 
/**
 * Execute a listener when a response is about to write headers.
 *
 * @param {Object} res
 * @return {Function} listener
 * @api public
 */
 
module.exports = function onHeaders(res, listener) {
  if (!res) {
    throw new TypeError('argument res is required')
  }
 
  if (typeof listener !== 'function') {
    throw new TypeError('argument listener must be a function')
  }
 
  res.writeHead = createWriteHead(res.writeHead, listener)
}
 
function createWriteHead(prevWriteHead, listener) {
  var fired = false;
 
  // return function with core name and argument list
  return function writeHead(statusCode) {
    // set headers from arguments
    var args = setWriteHeadHeaders.apply(this, arguments);
 
    // fire listener
    if (!fired) {
      fired = true
      listener.call(this)
 
      // pass-along an updated status code
      if (typeof args[0] === 'number' && this.statusCode !== args[0]) {
        args[0] = this.statusCode
        args.length = 1
      }
    }
 
    prevWriteHead.apply(this, args);
  }
}
 
function setWriteHeadHeaders(statusCode) {
  var length = arguments.length
  var headerIndex = length > 1 && typeof arguments[1] === 'string'
    ? 2
    : 1
 
  var headers = length >= headerIndex + 1
    ? arguments[headerIndex]
    : undefined
 
  this.statusCode = statusCode
 
  // the following block is from node.js core
  if (Array.isArray(headers)) {
    // handle array case
    for (var i = 0, len = headers.length; i < len; ++i) {
      this.setHeader(headers[i][0], headers[i][1])
    }
  } else if (headers) {
    // handle object case
    var keys = Object.keys(headers)
    for (var i = 0; i < keys.length; i++) {
      var k = keys[i]
      if (k) this.setHeader(k, headers[k])
    }
  }
 
  // copy leading arguments
  var args = new Array(Math.min(length, headerIndex))
  for (var i = 0; i < args.length; i++) {
    args[i] = arguments[i]
  }
 
  return args
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/vary/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/vary/

Statements: 19.35% (6 / 31)      Branches: 0% (0 / 27)      Functions: 0% (0 / 3)      Lines: 19.35% (6 / 31)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/vary/
File Statements Branches Functions Lines
index.js 19.35% (6 / 31) 0% (0 / 27) 0% (0 / 3) 19.35% (6 / 31)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/vary/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/compression/node_modules/vary/index.js

Statements: 19.35% (6 / 31)      Branches: 0% (0 / 27)      Functions: 0% (0 / 3)      Lines: 19.35% (6 / 31)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114                    1 1           1                     1                                                                                                                 1                       1                                
/*!
 * vary
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = vary;
module.exports.append = append;
 
/**
 * Variables.
 */
 
var separators = /[\(\)<>@,;:\\"\/\[\]\?=\{\}\u0020\u0009]/;
 
/**
 * Append a field to a vary header.
 *
 * @param {String} header
 * @param {String|Array} field
 * @return {String}
 * @api public
 */
 
function append(header, field) {
  if (typeof header !== 'string') {
    throw new TypeError('header argument is required');
  }
 
  if (!field) {
    throw new TypeError('field argument is required');
  }
 
  // get fields array
  var fields = !Array.isArray(field)
    ? parse(String(field))
    : field;
 
  // assert on invalid fields
  for (var i = 0; i < fields.length; i++) {
    if (separators.test(fields[i])) {
      throw new TypeError('field argument contains an invalid header');
    }
  }
 
  // existing, unspecified vary
  if (header === '*') {
    return header;
  }
 
  // enumerate current values
  var vals = parse(header.toLowerCase());
 
  // unspecified vary
  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
    return '*';
  }
 
  for (var i = 0; i < fields.length; i++) {
    field = fields[i].toLowerCase();
 
    // append value (case-preserving)
    if (vals.indexOf(field) === -1) {
      vals.push(field);
      header = header
        ? header + ', ' + fields[i]
        : fields[i];
    }
  }
 
  return header;
}
 
/**
 * Parse a vary header into an array.
 *
 * @param {String} header
 * @return {Array}
 * @api private
 */
 
function parse(header) {
  return header.trim().split(/ *, */);
}
 
/**
 * Mark that a request is varied on a header field.
 *
 * @param {Object} res
 * @param {String|Array} field
 * @api public
 */
 
function vary(res, field) {
  if (!res || !res.getHeader || !res.setHeader) {
    // quack quack
    throw new TypeError('res argument is required');
  }
 
  // get existing header
  var val = res.getHeader('Vary') || ''
  var header = Array.isArray(val)
    ? val.join(', ')
    : String(val);
 
  // set new header
  res.setHeader('Vary', append(header, field));
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/es6-shim/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/es6-shim/

Statements: 22.3% (264 / 1184)      Branches: 13.71% (96 / 700)      Functions: 22.7% (42 / 185)      Lines: 23.15% (256 / 1106)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/es6-shim/
File Statements Branches Functions Lines
es6-shim.js 22.3% (264 / 1184) 13.71% (96 / 700) 22.7% (42 / 185) 23.15% (256 / 1106)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/es6-shim/es6-shim.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/es6-shim/es6-shim.js

Statements: 22.3% (264 / 1184)      Branches: 13.71% (96 / 700)      Functions: 22.7% (42 / 185)      Lines: 23.15% (256 / 1106)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046                        1 1     1       1               1 2 2       1   2 2 2 2 2     2   2       1 1 1 1           1 1 1 1 1   1     1       1     1 1 1 1 1 1 1 1 1   1 1         7         1 95 47 47                         1 37 91 91           1 1                           1       1     1 10 10 10 10 10   5           1                           1 3         3 3 3   3   3     1                         6               6                                                                                                                                                                               1       1                     1                                                                                                                                           1                                                                     1 1 1 1   1     1 1 1         1     1                                                                                                         1         1       1             1                                                                                                         1   1 1                                           1       1                               1 1       1               1                                                                                                                     1   1 1 1             1           1           1                                                   1   1                                                                                                                                                                                                 1     1         1 1     1 1     1   1     1 1     1 1                                                                     1 1   1       1 1                                                         1                                         1   1                 1           1   1 1                                                     1             1                                   1 1               1                                                                                                                                                                                                                                                                                                                                                     1   1               1   1   1                                 1                                         1 1 1                                         1                   1             1                                                 1                               1                               1                                                                                       1 1                         1                                                                                                                                                                                                       1                                                                             1       1 1 1 1       1       1 1   1 1 1 1         1 1     1   1   1           1 2 8 8   2   1   1   1   1                                 1   3     1     1   1 2 2 2 2     1       1 2 2 2     1                                                           1   1 2 2     2 2       2   2   2             2                           2   1 1   2 2 2 2 2       1                     1                                                                                                                                                                                                                 1       1                                     1   1               1 1 1     1 1       1           1                     1   1 1   1 1 1 1 1         1 1 1 1                     1       1                         1                                                                               1 1                                         1 1   1     1   1               1                     1             1 1     1 1     1 1     1        
 /*!
  * https://github.com/paulmillr/es6-shim
  * @license es6-shim Copyright 2013-2014 by Paul Miller (http://paulmillr.com)
  *   and contributors,  MIT License
  * es6-shim: v0.21.1
  * see https://github.com/paulmillr/es6-shim/blob/master/LICENSE
  * Details and documentation:
  * https://github.com/paulmillr/es6-shim/
  */
 
// UMD (Universal Module Definition)
// see https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
  Iif (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(factory);
  } else Eif (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like enviroments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals (root is window)
    root.returnExports = factory();
  }
}(this, function () {
  'use strict';
 
  var isCallableWithoutNew = function (func) {
    try { func(); }
    catch (e) { return false; }
    return true;
  };
 
  var supportsSubclassing = function (C, f) {
    /* jshint proto:true */
    try {
      var Sub = function () { C.apply(this, arguments); };
      Iif (!Sub.__proto__) { return false; /* skip test on IE < 11 */ }
      Object.setPrototypeOf(Sub, C);
      Sub.prototype = Object.create(C.prototype, {
        constructor: { value: C }
      });
      return f(Sub);
    } catch (e) {
      return false;
    }
  };
 
  var arePropertyDescriptorsSupported = function () {
    try {
      Object.defineProperty({}, 'x', {});
      return true;
    } catch (e) { /* this is IE 8. */
      return false;
    }
  };
 
  var startsWithRejectsRegex = function () {
    var rejectsRegex = false;
    Eif (String.prototype.startsWith) {
      try {
        '/a/'.startsWith(/a/);
      } catch (e) { /* this is spec compliant */
        rejectsRegex = true;
      }
    }
    return rejectsRegex;
  };
 
  /*jshint evil: true */
  var getGlobal = new Function('return this;');
  /*jshint evil: false */
 
  var globals = getGlobal();
  var global_isFinite = globals.isFinite;
  var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported();
  var startsWithIsCompliant = startsWithRejectsRegex();
  var _slice = Array.prototype.slice;
  var _indexOf = Function.call.bind(String.prototype.indexOf);
  var _toString = Function.call.bind(Object.prototype.toString);
  var _hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
  var ArrayIterator; // make our implementation private
 
  var Symbol = globals.Symbol || {};
  var Type = {
    string: function (x) { return _toString(x) === '[object String]'; },
    regex: function (x) { return _toString(x) === '[object RegExp]'; },
    symbol: function (x) {
      /*jshint notypeof: true */
      return typeof globals.Symbol === 'function' && typeof x === 'symbol';
      /*jshint notypeof: false */
    }
  };
 
  var defineProperty = function (object, name, value, force) {
    if (!force && name in object) { return; }
    Eif (supportsDescriptors) {
      Object.defineProperty(object, name, {
        configurable: true,
        enumerable: false,
        writable: true,
        value: value
      });
    } else {
      object[name] = value;
    }
  };
 
  // Define configurable, writable and non-enumerable props
  // if they don’t exist.
  var defineProperties = function (object, map) {
    Object.keys(map).forEach(function (name) {
      var method = map[name];
      defineProperty(object, name, method, false);
    });
  };
 
  // Simple shim for Object.create on ES3 browsers
  // (unlike real shim, no attempt to support `prototype === null`)
  var create = Object.create || function (prototype, properties) {
    function Type() {}
    Type.prototype = prototype;
    var object = new Type();
    if (typeof properties !== 'undefined') {
      defineProperties(object, properties);
    }
    return object;
  };
 
  // This is a private name in the es6 spec, equal to '[Symbol.iterator]'
  // we're going to use an arbitrary _-prefixed name to make our shims
  // work properly with each other, even though we don't have full Iterator
  // support.  That is, `Array.from(map.keys())` will work, but we don't
  // pretend to export a "real" Iterator interface.
  var $iterator$ = Type.symbol(Symbol.iterator) ? Symbol.iterator : '_es6-shim iterator_';
  // Firefox ships a partial implementation using the name @@iterator.
  // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
  // So use that name if we detect it.
  Iif (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') {
    $iterator$ = '@@iterator';
  }
  var addIterator = function (prototype, impl) {
    if (!impl) { impl = function iterator() { return this; }; }
    var o = {};
    o[$iterator$] = impl;
    defineProperties(prototype, o);
    if (!prototype[$iterator$] && Type.symbol($iterator$)) {
      // implementations are buggy when $iterator$ is a Symbol
      prototype[$iterator$] = impl;
    }
  };
 
  // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js
  // can be replaced with require('is-arguments') if we ever use a build process instead
  var isArguments = function isArguments(value) {
    var str = _toString(value);
    var result = str === '[object Arguments]';
    if (!result) {
      result = str !== '[object Array]' &&
        value !== null &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        value.length >= 0 &&
        _toString(value.callee) === '[object Function]';
    }
    return result;
  };
 
  var emulateES6construct = function (o) {
    Iif (!ES.TypeIsObject(o)) { throw new TypeError('bad object'); }
    // es5 approximation to es6 subclass semantics: in es6, 'new Foo'
    // would invoke Foo.@@create to allocation/initialize the new object.
    // In es5 we just get the plain object.  So if we detect an
    // uninitialized object, invoke o.constructor.@@create
    Eif (!o._es6construct) {
      Eif (o.constructor && ES.IsCallable(o.constructor['@@create'])) {
        o = o.constructor['@@create'](o);
      }
      defineProperties(o, { _es6construct: true });
    }
    return o;
  };
 
  var ES = {
    CheckObjectCoercible: function (x, optMessage) {
      /* jshint eqnull:true */
      if (x == null) {
        throw new TypeError(optMessage || 'Cannot call method on ' + x);
      }
      return x;
    },
 
    TypeIsObject: function (x) {
      /* jshint eqnull:true */
      // this is expensive when it returns false; use this function
      // when you expect it to return true in the common case.
      return x != null && Object(x) === x;
    },
 
    ToObject: function (o, optMessage) {
      return Object(ES.CheckObjectCoercible(o, optMessage));
    },
 
    IsCallable: function (x) {
      return typeof x === 'function' &&
        // some versions of IE say that typeof /abc/ === 'function'
        _toString(x) === '[object Function]';
    },
 
    ToInt32: function (x) {
      return x >> 0;
    },
 
    ToUint32: function (x) {
      return x >>> 0;
    },
 
    ToInteger: function (value) {
      var number = +value;
      if (Number.isNaN(number)) { return 0; }
      if (number === 0 || !Number.isFinite(number)) { return number; }
      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
    },
 
    ToLength: function (value) {
      var len = ES.ToInteger(value);
      if (len <= 0) { return 0; } // includes converting -0 to +0
      if (len > Number.MAX_SAFE_INTEGER) { return Number.MAX_SAFE_INTEGER; }
      return len;
    },
 
    SameValue: function (a, b) {
      if (a === b) {
        // 0 === -0, but they are not identical.
        if (a === 0) { return 1 / a === 1 / b; }
        return true;
      }
      return Number.isNaN(a) && Number.isNaN(b);
    },
 
    SameValueZero: function (a, b) {
      // same as SameValue except for SameValueZero(+0, -0) == true
      return (a === b) || (Number.isNaN(a) && Number.isNaN(b));
    },
 
    IsIterable: function (o) {
      return ES.TypeIsObject(o) &&
        (typeof o[$iterator$] !== 'undefined' || isArguments(o));
    },
 
    GetIterator: function (o) {
      if (isArguments(o)) {
        // special case support for `arguments`
        return new ArrayIterator(o, 'value');
      }
      var itFn = o[$iterator$];
      if (!ES.IsCallable(itFn)) {
        throw new TypeError('value is not an iterable');
      }
      var it = itFn.call(o);
      if (!ES.TypeIsObject(it)) {
        throw new TypeError('bad iterator');
      }
      return it;
    },
 
    IteratorNext: function (it) {
      var result = arguments.length > 1 ? it.next(arguments[1]) : it.next();
      if (!ES.TypeIsObject(result)) {
        throw new TypeError('bad iterator');
      }
      return result;
    },
 
    Construct: function (C, args) {
      // CreateFromConstructor
      var obj;
      if (ES.IsCallable(C['@@create'])) {
        obj = C['@@create']();
      } else {
        // OrdinaryCreateFromConstructor
        obj = create(C.prototype || null);
      }
      // Mark that we've used the es6 construct path
      // (see emulateES6construct)
      defineProperties(obj, { _es6construct: true });
      // Call the constructor.
      var result = C.apply(obj, args);
      return ES.TypeIsObject(result) ? result : obj;
    }
  };
 
  var numberConversion = (function () {
    // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266
    // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200
 
    function roundToEven(n) {
      var w = Math.floor(n), f = n - w;
      if (f < 0.5) {
        return w;
      }
      if (f > 0.5) {
        return w + 1;
      }
      return w % 2 ? w + 1 : w;
    }
 
    function packIEEE754(v, ebits, fbits) {
      var bias = (1 << (ebits - 1)) - 1,
        s, e, f,
        i, bits, str, bytes;
 
      // Compute sign, exponent, fraction
      if (v !== v) {
        // NaN
        // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
        e = (1 << ebits) - 1;
        f = Math.pow(2, fbits - 1);
        s = 0;
      } else if (v === Infinity || v === -Infinity) {
        e = (1 << ebits) - 1;
        f = 0;
        s = (v < 0) ? 1 : 0;
      } else if (v === 0) {
        e = 0;
        f = 0;
        s = (1 / v === -Infinity) ? 1 : 0;
      } else {
        s = v < 0;
        v = Math.abs(v);
 
        if (v >= Math.pow(2, 1 - bias)) {
          e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023);
          f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits));
          if (f / Math.pow(2, fbits) >= 2) {
            e = e + 1;
            f = 1;
          }
          if (e > bias) {
            // Overflow
            e = (1 << ebits) - 1;
            f = 0;
          } else {
            // Normal
            e = e + bias;
            f = f - Math.pow(2, fbits);
          }
        } else {
          // Subnormal
          e = 0;
          f = roundToEven(v / Math.pow(2, 1 - bias - fbits));
        }
      }
 
      // Pack sign, exponent, fraction
      bits = [];
      for (i = fbits; i; i -= 1) {
        bits.push(f % 2 ? 1 : 0);
        f = Math.floor(f / 2);
      }
      for (i = ebits; i; i -= 1) {
        bits.push(e % 2 ? 1 : 0);
        e = Math.floor(e / 2);
      }
      bits.push(s ? 1 : 0);
      bits.reverse();
      str = bits.join('');
 
      // Bits to bytes
      bytes = [];
      while (str.length) {
        bytes.push(parseInt(str.slice(0, 8), 2));
        str = str.slice(8);
      }
      return bytes;
    }
 
    function unpackIEEE754(bytes, ebits, fbits) {
      // Bytes to bits
      var bits = [], i, j, b, str,
          bias, s, e, f;
 
      for (i = bytes.length; i; i -= 1) {
        b = bytes[i - 1];
        for (j = 8; j; j -= 1) {
          bits.push(b % 2 ? 1 : 0);
          b = b >> 1;
        }
      }
      bits.reverse();
      str = bits.join('');
 
      // Unpack sign, exponent, fraction
      bias = (1 << (ebits - 1)) - 1;
      s = parseInt(str.slice(0, 1), 2) ? -1 : 1;
      e = parseInt(str.slice(1, 1 + ebits), 2);
      f = parseInt(str.slice(1 + ebits), 2);
 
      // Produce number
      if (e === (1 << ebits) - 1) {
        return f !== 0 ? NaN : s * Infinity;
      } else if (e > 0) {
        // Normalized
        return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits));
      } else if (f !== 0) {
        // Denormalized
        return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits));
      } else {
        return s < 0 ? -0 : 0;
      }
    }
 
    function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); }
    function packFloat64(v) { return packIEEE754(v, 11, 52); }
    function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); }
    function packFloat32(v) { return packIEEE754(v, 8, 23); }
 
    var conversions = {
      toFloat32: function (num) { return unpackFloat32(packFloat32(num)); }
    };
    Eif (typeof Float32Array !== 'undefined') {
      var float32array = new Float32Array(1);
      conversions.toFloat32 = function (num) {
        float32array[0] = num;
        return float32array[0];
      };
    }
    return conversions;
  }());
 
  defineProperties(String, {
    fromCodePoint: function fromCodePoint(_) { // length = 1
      var result = [];
      var next;
      for (var i = 0, length = arguments.length; i < length; i++) {
        next = Number(arguments[i]);
        if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) {
          throw new RangeError('Invalid code point ' + next);
        }
 
        if (next < 0x10000) {
          result.push(String.fromCharCode(next));
        } else {
          next -= 0x10000;
          result.push(String.fromCharCode((next >> 10) + 0xD800));
          result.push(String.fromCharCode((next % 0x400) + 0xDC00));
        }
      }
      return result.join('');
    },
 
    raw: function raw(callSite) { // raw.length===1
      var cooked = ES.ToObject(callSite, 'bad callSite');
      var rawValue = cooked.raw;
      var rawString = ES.ToObject(rawValue, 'bad raw value');
      var len = rawString.length;
      var literalsegments = ES.ToLength(len);
      if (literalsegments <= 0) {
        return '';
      }
 
      var stringElements = [];
      var nextIndex = 0;
      var nextKey, next, nextSeg, nextSub;
      while (nextIndex < literalsegments) {
        nextKey = String(nextIndex);
        next = rawString[nextKey];
        nextSeg = String(next);
        stringElements.push(nextSeg);
        if (nextIndex + 1 >= literalsegments) {
          break;
        }
        next = nextIndex + 1 < arguments.length ? arguments[nextIndex + 1] : '';
        nextSub = String(next);
        stringElements.push(nextSub);
        nextIndex++;
      }
      return stringElements.join('');
    }
  });
 
  // Firefox 31 reports this function's length as 0
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1062484
  Iif (String.fromCodePoint.length !== 1) {
    var originalFromCodePoint = Function.apply.bind(String.fromCodePoint);
    defineProperty(String, 'fromCodePoint', function (_) { return originalFromCodePoint(this, arguments); }, true);
  }
 
  var StringShims = {
    // Fast repeat, uses the `Exponentiation by squaring` algorithm.
    // Perf: http://jsperf.com/string-repeat2/2
    repeat: (function () {
      var repeat = function (s, times) {
        if (times < 1) { return ''; }
        if (times % 2) { return repeat(s, times - 1) + s; }
        var half = repeat(s, times / 2);
        return half + half;
      };
 
      return function (times) {
        var thisStr = String(ES.CheckObjectCoercible(this));
        times = ES.ToInteger(times);
        if (times < 0 || times === Infinity) {
          throw new RangeError('Invalid String#repeat value');
        }
        return repeat(thisStr, times);
      };
    })(),
 
    startsWith: function (searchStr) {
      var thisStr = String(ES.CheckObjectCoercible(this));
      if (Type.regex(searchStr)) {
        throw new TypeError('Cannot call method "startsWith" with a regex');
      }
      searchStr = String(searchStr);
      var startArg = arguments.length > 1 ? arguments[1] : void 0;
      var start = Math.max(ES.ToInteger(startArg), 0);
      return thisStr.slice(start, start + searchStr.length) === searchStr;
    },
 
    endsWith: function (searchStr) {
      var thisStr = String(ES.CheckObjectCoercible(this));
      if (Type.regex(searchStr)) {
        throw new TypeError('Cannot call method "endsWith" with a regex');
      }
      searchStr = String(searchStr);
      var thisLen = thisStr.length;
      var posArg = arguments.length > 1 ? arguments[1] : void 0;
      var pos = typeof posArg === 'undefined' ? thisLen : ES.ToInteger(posArg);
      var end = Math.min(Math.max(pos, 0), thisLen);
      return thisStr.slice(end - searchStr.length, end) === searchStr;
    },
 
    includes: function includes(searchString) {
      var position = arguments.length > 1 ? arguments[1] : void 0;
      // Somehow this trick makes method 100% compat with the spec.
      return _indexOf(this, searchString, position) !== -1;
    },
 
    codePointAt: function (pos) {
      var thisStr = String(ES.CheckObjectCoercible(this));
      var position = ES.ToInteger(pos);
      var length = thisStr.length;
      if (position < 0 || position >= length) { return; }
      var first = thisStr.charCodeAt(position);
      var isEnd = (position + 1 === length);
      if (first < 0xD800 || first > 0xDBFF || isEnd) { return first; }
      var second = thisStr.charCodeAt(position + 1);
      if (second < 0xDC00 || second > 0xDFFF) { return first; }
      return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000;
    }
  };
  defineProperties(String.prototype, StringShims);
 
  var hasStringTrimBug = '\u0085'.trim().length !== 1;
  Iif (hasStringTrimBug) {
    var originalStringTrim = String.prototype.trim;
    delete String.prototype.trim;
    // whitespace from: http://es5.github.io/#x15.5.4.20
    // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324
    var ws = [
      '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003',
      '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028',
      '\u2029\uFEFF'
    ].join('');
    var trimRegexp = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g');
    defineProperties(String.prototype, {
      trim: function () {
        if (typeof this === 'undefined' || this === null) {
          throw new TypeError("can't convert " + this + ' to object');
        }
        return String(this).replace(trimRegexp, '');
      }
    });
  }
 
  // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator
  var StringIterator = function (s) {
    this._s = String(ES.CheckObjectCoercible(s));
    this._i = 0;
  };
  StringIterator.prototype.next = function () {
    var s = this._s, i = this._i;
    if (typeof s === 'undefined' || i >= s.length) {
      this._s = void 0;
      return { value: void 0, done: true };
    }
    var first = s.charCodeAt(i), second, len;
    if (first < 0xD800 || first > 0xDBFF || (i + 1) == s.length) {
      len = 1;
    } else {
      second = s.charCodeAt(i + 1);
      len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2;
    }
    this._i = i + len;
    return { value: s.substr(i, len), done: false };
  };
  addIterator(StringIterator.prototype);
  addIterator(String.prototype, function () {
    return new StringIterator(this);
  });
 
  Iif (!startsWithIsCompliant) {
    // Firefox has a noncompliant startsWith implementation
    defineProperties(String.prototype, {
      startsWith: StringShims.startsWith,
      endsWith: StringShims.endsWith
    });
  }
 
  var ArrayShims = {
    from: function (iterable) {
      var mapFn = arguments.length > 1 ? arguments[1] : void 0;
 
      var list = ES.ToObject(iterable, 'bad iterable');
      if (typeof mapFn !== 'undefined' && !ES.IsCallable(mapFn)) {
        throw new TypeError('Array.from: when provided, the second argument must be a function');
      }
 
      var hasThisArg = arguments.length > 2;
      var thisArg = hasThisArg ? arguments[2] : void 0;
 
      var usingIterator = ES.IsIterable(list);
      // does the spec really mean that Arrays should use ArrayIterator?
      // https://bugs.ecmascript.org/show_bug.cgi?id=2416
      //if (Array.isArray(list)) { usingIterator=false; }
 
      var length;
      var result, i, value;
      if (usingIterator) {
        i = 0;
        result = ES.IsCallable(this) ? Object(new this()) : [];
        var it = usingIterator ? ES.GetIterator(list) : null;
        var iterationValue;
 
        do {
          iterationValue = ES.IteratorNext(it);
          if (!iterationValue.done) {
            value = iterationValue.value;
            if (mapFn) {
              result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i);
            } else {
              result[i] = value;
            }
            i += 1;
          }
        } while (!iterationValue.done);
        length = i;
      } else {
        length = ES.ToLength(list.length);
        result = ES.IsCallable(this) ? Object(new this(length)) : new Array(length);
        for (i = 0; i < length; ++i) {
          value = list[i];
          if (mapFn) {
            result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i);
          } else {
            result[i] = value;
          }
        }
      }
 
      result.length = length;
      return result;
    },
 
    of: function () {
      return Array.from(arguments);
    }
  };
  defineProperties(Array, ArrayShims);
 
  var arrayFromSwallowsNegativeLengths = function () {
    try {
      return Array.from({ length: -1 }).length === 0;
    } catch (e) {
      return false;
    }
  };
  // Fixes a Firefox bug in v32
  // https://bugzilla.mozilla.org/show_bug.cgi?id=1063993
  Iif (!arrayFromSwallowsNegativeLengths()) {
    defineProperty(Array, 'from', ArrayShims.from, true);
  }
 
  // Our ArrayIterator is private; see
  // https://github.com/paulmillr/es6-shim/issues/252
  ArrayIterator = function (array, kind) {
      this.i = 0;
      this.array = array;
      this.kind = kind;
  };
 
  defineProperties(ArrayIterator.prototype, {
    next: function () {
      var i = this.i, array = this.array;
      if (!(this instanceof ArrayIterator)) {
        throw new TypeError('Not an ArrayIterator');
      }
      if (typeof array !== 'undefined') {
        var len = ES.ToLength(array.length);
        for (; i < len; i++) {
          var kind = this.kind;
          var retval;
          if (kind === 'key') {
            retval = i;
          } else if (kind === 'value') {
            retval = array[i];
          } else if (kind === 'entry') {
            retval = [i, array[i]];
          }
          this.i = i + 1;
          return { value: retval, done: false };
        }
      }
      this.array = void 0;
      return { value: void 0, done: true };
    }
  });
  addIterator(ArrayIterator.prototype);
 
  var ArrayPrototypeShims = {
    copyWithin: function (target, start) {
      var end = arguments[2]; // copyWithin.length must be 2
      var o = ES.ToObject(this);
      var len = ES.ToLength(o.length);
      target = ES.ToInteger(target);
      start = ES.ToInteger(start);
      var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len);
      var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
      end = typeof end === 'undefined' ? len : ES.ToInteger(end);
      var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
      var count = Math.min(fin - from, len - to);
      var direction = 1;
      if (from < to && to < (from + count)) {
        direction = -1;
        from += count - 1;
        to += count - 1;
      }
      while (count > 0) {
        if (_hasOwnProperty(o, from)) {
          o[to] = o[from];
        } else {
          delete o[from];
        }
        from += direction;
        to += direction;
        count -= 1;
      }
      return o;
    },
 
    fill: function (value) {
      var start = arguments.length > 1 ? arguments[1] : void 0;
      var end = arguments.length > 2 ? arguments[2] : void 0;
      var O = ES.ToObject(this);
      var len = ES.ToLength(O.length);
      start = ES.ToInteger(typeof start === 'undefined' ? 0 : start);
      end = ES.ToInteger(typeof end === 'undefined' ? len : end);
 
      var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
      var relativeEnd = end < 0 ? len + end : end;
 
      for (var i = relativeStart; i < len && i < relativeEnd; ++i) {
        O[i] = value;
      }
      return O;
    },
 
    find: function find(predicate) {
      var list = ES.ToObject(this);
      var length = ES.ToLength(list.length);
      if (!ES.IsCallable(predicate)) {
        throw new TypeError('Array#find: predicate must be a function');
      }
      var thisArg = arguments.length > 1 ? arguments[1] : null;
      for (var i = 0, value; i < length; i++) {
        value = list[i];
        if (thisArg) {
          if (predicate.call(thisArg, value, i, list)) { return value; }
        } else {
          if (predicate(value, i, list)) { return value; }
        }
      }
      return;
    },
 
    findIndex: function findIndex(predicate) {
      var list = ES.ToObject(this);
      var length = ES.ToLength(list.length);
      if (!ES.IsCallable(predicate)) {
        throw new TypeError('Array#findIndex: predicate must be a function');
      }
      var thisArg = arguments.length > 1 ? arguments[1] : null;
      for (var i = 0; i < length; i++) {
        if (thisArg) {
          if (predicate.call(thisArg, list[i], i, list)) { return i; }
        } else {
          if (predicate(list[i], i, list)) { return i; }
        }
      }
      return -1;
    },
 
    keys: function () {
      return new ArrayIterator(this, 'key');
    },
 
    values: function () {
      return new ArrayIterator(this, 'value');
    },
 
    entries: function () {
      return new ArrayIterator(this, 'entry');
    }
  };
  // Safari 7.1 defines Array#keys and Array#entries natively,
  // but the resulting ArrayIterator objects don't have a "next" method.
  Iif (Array.prototype.keys && !ES.IsCallable([1].keys().next)) {
    delete Array.prototype.keys;
  }
  Iif (Array.prototype.entries && !ES.IsCallable([1].entries().next)) {
    delete Array.prototype.entries;
  }
 
  // Chrome 38 defines Array#keys and Array#entries, and Array#@@iterator, but not Array#values
  Eif (Array.prototype.keys && Array.prototype.entries && !Array.prototype.values && Array.prototype[$iterator$]) {
    defineProperties(Array.prototype, {
      values: Array.prototype[$iterator$]
    });
    Eif (Type.symbol(Symbol.unscopables)) {
      Array.prototype[Symbol.unscopables].values = true;
    }
  }
  defineProperties(Array.prototype, ArrayPrototypeShims);
 
  addIterator(Array.prototype, function () { return this.values(); });
  // Chrome defines keys/values/entries on Array, but doesn't give us
  // any way to identify its iterator.  So add our own shimmed field.
  Eif (Object.getPrototypeOf) {
    addIterator(Object.getPrototypeOf([].values()));
  }
 
  var maxSafeInteger = Math.pow(2, 53) - 1;
  defineProperties(Number, {
    MAX_SAFE_INTEGER: maxSafeInteger,
    MIN_SAFE_INTEGER: -maxSafeInteger,
    EPSILON: 2.220446049250313e-16,
 
    parseInt: globals.parseInt,
    parseFloat: globals.parseFloat,
 
    isFinite: function (value) {
      return typeof value === 'number' && global_isFinite(value);
    },
 
    isInteger: function (value) {
      return Number.isFinite(value) &&
        ES.ToInteger(value) === value;
    },
 
    isSafeInteger: function (value) {
      return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
    },
 
    isNaN: function (value) {
      // NaN !== NaN, but they are identical.
      // NaNs are the only non-reflexive value, i.e., if x !== x,
      // then x is NaN.
      // isNaN is broken: it converts its argument to number, so
      // isNaN('foo') => true
      return value !== value;
    }
  });
 
  // Work around bugs in Array#find and Array#findIndex -- early
  // implementations skipped holes in sparse arrays. (Note that the
  // implementations of find/findIndex indirectly use shimmed
  // methods of Number, so this test has to happen down here.)
  Eif (![, 1].find(function (item, idx) { return idx === 0; })) {
    defineProperty(Array.prototype, 'find', ArrayPrototypeShims.find, true);
  }
  Iif ([, 1].findIndex(function (item, idx) { return idx === 0; }) !== 0) {
    defineProperty(Array.prototype, 'findIndex', ArrayPrototypeShims.findIndex, true);
  }
 
  Eif (supportsDescriptors) {
    defineProperties(Object, {
      getPropertyDescriptor: function (subject, name) {
        var pd = Object.getOwnPropertyDescriptor(subject, name);
        var proto = Object.getPrototypeOf(subject);
        while (typeof pd === 'undefined' && proto !== null) {
          pd = Object.getOwnPropertyDescriptor(proto, name);
          proto = Object.getPrototypeOf(proto);
        }
        return pd;
      },
 
      getPropertyNames: function (subject) {
        var result = Object.getOwnPropertyNames(subject);
        var proto = Object.getPrototypeOf(subject);
 
        var addProperty = function (property) {
          if (result.indexOf(property) === -1) {
            result.push(property);
          }
        };
 
        while (proto !== null) {
          Object.getOwnPropertyNames(proto).forEach(addProperty);
          proto = Object.getPrototypeOf(proto);
        }
        return result;
      }
    });
 
    defineProperties(Object, {
      // 19.1.3.1
      assign: function (target, source) {
        if (!ES.TypeIsObject(target)) {
          throw new TypeError('target must be an object');
        }
        return Array.prototype.reduce.call(arguments, function (target, source) {
          return Object.keys(Object(source)).reduce(function (target, key) {
            target[key] = source[key];
            return target;
          }, target);
        });
      },
 
      is: function (a, b) {
        return ES.SameValue(a, b);
      },
 
      // 19.1.3.9
      // shim from https://gist.github.com/WebReflection/5593554
      setPrototypeOf: (function (Object, magic) {
        var set;
 
        var checkArgs = function (O, proto) {
          if (!ES.TypeIsObject(O)) {
            throw new TypeError('cannot set prototype on a non-object');
          }
          if (!(proto === null || ES.TypeIsObject(proto))) {
            throw new TypeError('can only set prototype to an object or null' + proto);
          }
        };
 
        var setPrototypeOf = function (O, proto) {
          checkArgs(O, proto);
          set.call(O, proto);
          return O;
        };
 
        try {
          // this works already in Firefox and Safari
          set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set;
          set.call({}, null);
        } catch (e) {
          if (Object.prototype !== {}[magic]) {
            // IE < 11 cannot be shimmed
            return;
          }
          // probably Chrome or some old Mobile stock browser
          set = function (proto) {
            this[magic] = proto;
          };
          // please note that this will **not** work
          // in those browsers that do not inherit
          // __proto__ by mistake from Object.prototype
          // in these cases we should probably throw an error
          // or at least be informed about the issue
          setPrototypeOf.polyfill = setPrototypeOf(
            setPrototypeOf({}, null),
            Object.prototype
          ) instanceof Object;
          // setPrototypeOf.polyfill === true means it works as meant
          // setPrototypeOf.polyfill === false means it's not 100% reliable
          // setPrototypeOf.polyfill === undefined
          // or
          // setPrototypeOf.polyfill ==  null means it's not a polyfill
          // which means it works as expected
          // we can even delete Object.prototype.__proto__;
        }
        return setPrototypeOf;
      })(Object, '__proto__')
    });
  }
 
  // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work,
  // but Object.create(null) does.
  Iif (Object.setPrototypeOf && Object.getPrototypeOf &&
      Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null &&
      Object.getPrototypeOf(Object.create(null)) === null) {
    (function () {
      var FAKENULL = Object.create(null);
      var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf;
      Object.getPrototypeOf = function (o) {
        var result = gpo(o);
        return result === FAKENULL ? null : result;
      };
      Object.setPrototypeOf = function (o, p) {
        if (p === null) { p = FAKENULL; }
        return spo(o, p);
      };
      Object.setPrototypeOf.polyfill = false;
    })();
  }
 
  try {
    Object.keys('foo');
  } catch (e) {
    var originalObjectKeys = Object.keys;
    Object.keys = function (obj) {
      return originalObjectKeys(ES.ToObject(obj));
    };
  }
 
  var MathShims = {
    acosh: function (value) {
      value = Number(value);
      if (Number.isNaN(value) || value < 1) { return NaN; }
      if (value === 1) { return 0; }
      if (value === Infinity) { return value; }
      return Math.log(value + Math.sqrt(value * value - 1));
    },
 
    asinh: function (value) {
      value = Number(value);
      if (value === 0 || !global_isFinite(value)) {
        return value;
      }
      return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1));
    },
 
    atanh: function (value) {
      value = Number(value);
      if (Number.isNaN(value) || value < -1 || value > 1) {
        return NaN;
      }
      if (value === -1) { return -Infinity; }
      if (value === 1) { return Infinity; }
      if (value === 0) { return value; }
      return 0.5 * Math.log((1 + value) / (1 - value));
    },
 
    cbrt: function (value) {
      value = Number(value);
      if (value === 0) { return value; }
      var negate = value < 0, result;
      if (negate) { value = -value; }
      result = Math.pow(value, 1 / 3);
      return negate ? -result : result;
    },
 
    clz32: function (value) {
      // See https://bugs.ecmascript.org/show_bug.cgi?id=2465
      value = Number(value);
      var number = ES.ToUint32(value);
      if (number === 0) {
        return 32;
      }
      return 32 - (number).toString(2).length;
    },
 
    cosh: function (value) {
      value = Number(value);
      if (value === 0) { return 1; } // +0 or -0
      if (Number.isNaN(value)) { return NaN; }
      if (!global_isFinite(value)) { return Infinity; }
      if (value < 0) { value = -value; }
      if (value > 21) { return Math.exp(value) / 2; }
      return (Math.exp(value) + Math.exp(-value)) / 2;
    },
 
    expm1: function (value) {
      value = Number(value);
      if (value === -Infinity) { return -1; }
      if (!global_isFinite(value) || value === 0) { return value; }
      return Math.exp(value) - 1;
    },
 
    hypot: function (x, y) {
      var anyNaN = false;
      var allZero = true;
      var anyInfinity = false;
      var numbers = [];
      Array.prototype.every.call(arguments, function (arg) {
        var num = Number(arg);
        if (Number.isNaN(num)) {
          anyNaN = true;
        } else if (num === Infinity || num === -Infinity) {
          anyInfinity = true;
        } else if (num !== 0) {
          allZero = false;
        }
        if (anyInfinity) {
          return false;
        } else if (!anyNaN) {
          numbers.push(Math.abs(num));
        }
        return true;
      });
      if (anyInfinity) { return Infinity; }
      if (anyNaN) { return NaN; }
      if (allZero) { return 0; }
 
      numbers.sort(function (a, b) { return b - a; });
      var largest = numbers[0];
      var divided = numbers.map(function (number) { return number / largest; });
      var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0);
      return largest * Math.sqrt(sum);
    },
 
    log2: function (value) {
      return Math.log(value) * Math.LOG2E;
    },
 
    log10: function (value) {
      return Math.log(value) * Math.LOG10E;
    },
 
    log1p: function (value) {
      value = Number(value);
      if (value < -1 || Number.isNaN(value)) { return NaN; }
      if (value === 0 || value === Infinity) { return value; }
      if (value === -1) { return -Infinity; }
      var result = 0;
      var n = 50;
 
      if (value < 0 || value > 1) { return Math.log(1 + value); }
      for (var i = 1; i < n; i++) {
        if ((i % 2) === 0) {
          result -= Math.pow(value, i) / i;
        } else {
          result += Math.pow(value, i) / i;
        }
      }
 
      return result;
    },
 
    sign: function (value) {
      var number = +value;
      if (number === 0) { return number; }
      if (Number.isNaN(number)) { return number; }
      return number < 0 ? -1 : 1;
    },
 
    sinh: function (value) {
      value = Number(value);
      if (!global_isFinite(value) || value === 0) { return value; }
      return (Math.exp(value) - Math.exp(-value)) / 2;
    },
 
    tanh: function (value) {
      value = Number(value);
      if (Number.isNaN(value) || value === 0) { return value; }
      if (value === Infinity) { return 1; }
      if (value === -Infinity) { return -1; }
      return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value));
    },
 
    trunc: function (value) {
      var number = Number(value);
      return number < 0 ? -Math.floor(-number) : Math.floor(number);
    },
 
    imul: function (x, y) {
      // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
      x = ES.ToUint32(x);
      y = ES.ToUint32(y);
      var ah  = (x >>> 16) & 0xffff;
      var al = x & 0xffff;
      var bh  = (y >>> 16) & 0xffff;
      var bl = y & 0xffff;
      // the shift by 0 fixes the sign on the high part
      // the final |0 converts the unsigned value into a signed value
      return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);
    },
 
    fround: function (x) {
      if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) {
        return x;
      }
      var num = Number(x);
      return numberConversion.toFloat32(num);
    }
  };
  defineProperties(Math, MathShims);
 
  Iif (Math.imul(0xffffffff, 5) !== -5) {
    // Safari 6.1, at least, reports "0" for this value
    Math.imul = MathShims.imul;
  }
 
  // Promises
  // Simplest possible implementation; use a 3rd-party library if you
  // want the best possible speed and/or long stack traces.
  var PromiseShim = (function () {
 
    var Promise, Promise$prototype;
 
    ES.IsPromise = function (promise) {
      if (!ES.TypeIsObject(promise)) {
        return false;
      }
      if (!promise._promiseConstructor) {
        // _promiseConstructor is a bit more unique than _status, so we'll
        // check that instead of the [[PromiseStatus]] internal field.
        return false;
      }
      if (typeof promise._status === 'undefined') {
        return false; // uninitialized
      }
      return true;
    };
 
    // "PromiseCapability" in the spec is what most promise implementations
    // call a "deferred".
    var PromiseCapability = function (C) {
      if (!ES.IsCallable(C)) {
        throw new TypeError('bad promise constructor');
      }
      var capability = this;
      var resolver = function (resolve, reject) {
        capability.resolve = resolve;
        capability.reject = reject;
      };
      capability.promise = ES.Construct(C, [resolver]);
      // see https://bugs.ecmascript.org/show_bug.cgi?id=2478
      if (!capability.promise._es6construct) {
        throw new TypeError('bad promise constructor');
      }
      if (!(ES.IsCallable(capability.resolve) &&
            ES.IsCallable(capability.reject))) {
        throw new TypeError('bad promise constructor');
      }
    };
 
    // find an appropriate setImmediate-alike
    var setTimeout = globals.setTimeout;
    var makeZeroTimeout;
    Iif (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) {
      makeZeroTimeout = function () {
        // from http://dbaron.org/log/20100309-faster-timeouts
        var timeouts = [];
        var messageName = 'zero-timeout-message';
        var setZeroTimeout = function (fn) {
          timeouts.push(fn);
          window.postMessage(messageName, '*');
        };
        var handleMessage = function (event) {
          if (event.source == window && event.data == messageName) {
            event.stopPropagation();
            if (timeouts.length === 0) { return; }
            var fn = timeouts.shift();
            fn();
          }
        };
        window.addEventListener('message', handleMessage, true);
        return setZeroTimeout;
      };
    }
    var makePromiseAsap = function () {
      // An efficient task-scheduler based on a pre-existing Promise
      // implementation, which we can use even if we override the
      // global Promise below (in order to workaround bugs)
      // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671
      var P = globals.Promise;
      return P && P.resolve && function (task) {
        return P.resolve().then(task);
      };
    };
    var enqueue = ES.IsCallable(globals.setImmediate) ?
      globals.setImmediate.bind(globals) :
      typeof process === 'object' && process.nextTick ? process.nextTick :
      makePromiseAsap() ||
      (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() :
      function (task) { setTimeout(task, 0); }); // fallback
 
    var triggerPromiseReactions = function (reactions, x) {
      reactions.forEach(function (reaction) {
        enqueue(function () {
          // PromiseReactionTask
          var handler = reaction.handler;
          var capability = reaction.capability;
          var resolve = capability.resolve;
          var reject = capability.reject;
          try {
            var result = handler(x);
            if (result === capability.promise) {
              throw new TypeError('self resolution');
            }
            var updateResult =
              updatePromiseFromPotentialThenable(result, capability);
            if (!updateResult) {
              resolve(result);
            }
          } catch (e) {
            reject(e);
          }
        });
      });
    };
 
    var updatePromiseFromPotentialThenable = function (x, capability) {
      if (!ES.TypeIsObject(x)) {
        return false;
      }
      var resolve = capability.resolve;
      var reject = capability.reject;
      try {
        var then = x.then; // only one invocation of accessor
        if (!ES.IsCallable(then)) { return false; }
        then.call(x, resolve, reject);
      } catch (e) {
        reject(e);
      }
      return true;
    };
 
    var promiseResolutionHandler = function (promise, onFulfilled, onRejected) {
      return function (x) {
        if (x === promise) {
          return onRejected(new TypeError('self resolution'));
        }
        var C = promise._promiseConstructor;
        var capability = new PromiseCapability(C);
        var updateResult = updatePromiseFromPotentialThenable(x, capability);
        if (updateResult) {
          return capability.promise.then(onFulfilled, onRejected);
        } else {
          return onFulfilled(x);
        }
      };
    };
 
    Promise = function (resolver) {
      var promise = this;
      promise = emulateES6construct(promise);
      if (!promise._promiseConstructor) {
        // we use _promiseConstructor as a stand-in for the internal
        // [[PromiseStatus]] field; it's a little more unique.
        throw new TypeError('bad promise');
      }
      if (typeof promise._status !== 'undefined') {
        throw new TypeError('promise already initialized');
      }
      // see https://bugs.ecmascript.org/show_bug.cgi?id=2482
      if (!ES.IsCallable(resolver)) {
        throw new TypeError('not a valid resolver');
      }
      promise._status = 'unresolved';
      promise._resolveReactions = [];
      promise._rejectReactions = [];
 
      var resolve = function (resolution) {
        if (promise._status !== 'unresolved') { return; }
        var reactions = promise._resolveReactions;
        promise._result = resolution;
        promise._resolveReactions = void 0;
        promise._rejectReactions = void 0;
        promise._status = 'has-resolution';
        triggerPromiseReactions(reactions, resolution);
      };
      var reject = function (reason) {
        if (promise._status !== 'unresolved') { return; }
        var reactions = promise._rejectReactions;
        promise._result = reason;
        promise._resolveReactions = void 0;
        promise._rejectReactions = void 0;
        promise._status = 'has-rejection';
        triggerPromiseReactions(reactions, reason);
      };
      try {
        resolver(resolve, reject);
      } catch (e) {
        reject(e);
      }
      return promise;
    };
    Promise$prototype = Promise.prototype;
    var _promiseAllResolver = function (index, values, capability, remaining) {
      var done = false;
      return function (x) {
        if (done) { return; } // protect against being called multiple times
        done = true;
        values[index] = x;
        if ((--remaining.count) === 0) {
          var resolve = capability.resolve;
          resolve(values); // call w/ this===undefined
        }
      };
    };
 
    defineProperties(Promise, {
      '@@create': function (obj) {
        var constructor = this;
        // AllocatePromise
        // The `obj` parameter is a hack we use for es5
        // compatibility.
        var prototype = constructor.prototype || Promise$prototype;
        obj = obj || create(prototype);
        defineProperties(obj, {
          _status: void 0,
          _result: void 0,
          _resolveReactions: void 0,
          _rejectReactions: void 0,
          _promiseConstructor: void 0
        });
        obj._promiseConstructor = constructor;
        return obj;
      },
 
      all: function all(iterable) {
        var C = this;
        var capability = new PromiseCapability(C);
        var resolve = capability.resolve;
        var reject = capability.reject;
        try {
          if (!ES.IsIterable(iterable)) {
            throw new TypeError('bad iterable');
          }
          var it = ES.GetIterator(iterable);
          var values = [], remaining = { count: 1 };
          for (var index = 0; ; index++) {
            var next = ES.IteratorNext(it);
            if (next.done) {
              break;
            }
            var nextPromise = C.resolve(next.value);
            var resolveElement = _promiseAllResolver(
              index, values, capability, remaining
            );
            remaining.count++;
            nextPromise.then(resolveElement, capability.reject);
          }
          if ((--remaining.count) === 0) {
            resolve(values); // call w/ this===undefined
          }
        } catch (e) {
          reject(e);
        }
        return capability.promise;
      },
 
      race: function race(iterable) {
        var C = this;
        var capability = new PromiseCapability(C);
        var resolve = capability.resolve;
        var reject = capability.reject;
        try {
          if (!ES.IsIterable(iterable)) {
            throw new TypeError('bad iterable');
          }
          var it = ES.GetIterator(iterable);
          while (true) {
            var next = ES.IteratorNext(it);
            if (next.done) {
              // If iterable has no items, resulting promise will never
              // resolve; see:
              // https://github.com/domenic/promises-unwrapping/issues/75
              // https://bugs.ecmascript.org/show_bug.cgi?id=2515
              break;
            }
            var nextPromise = C.resolve(next.value);
            nextPromise.then(resolve, reject);
          }
        } catch (e) {
          reject(e);
        }
        return capability.promise;
      },
 
      reject: function reject(reason) {
        var C = this;
        var capability = new PromiseCapability(C);
        var rejectPromise = capability.reject;
        rejectPromise(reason); // call with this===undefined
        return capability.promise;
      },
 
      resolve: function resolve(v) {
        var C = this;
        if (ES.IsPromise(v)) {
          var constructor = v._promiseConstructor;
          if (constructor === C) { return v; }
        }
        var capability = new PromiseCapability(C);
        var resolvePromise = capability.resolve;
        resolvePromise(v); // call with this===undefined
        return capability.promise;
      }
    });
 
    defineProperties(Promise$prototype, {
      'catch': function (onRejected) {
        return this.then(void 0, onRejected);
      },
 
      then: function then(onFulfilled, onRejected) {
        var promise = this;
        if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); }
        // this.constructor not this._promiseConstructor; see
        // https://bugs.ecmascript.org/show_bug.cgi?id=2513
        var C = this.constructor;
        var capability = new PromiseCapability(C);
        if (!ES.IsCallable(onRejected)) {
          onRejected = function (e) { throw e; };
        }
        if (!ES.IsCallable(onFulfilled)) {
          onFulfilled = function (x) { return x; };
        }
        var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected);
        var resolveReaction = { capability: capability, handler: resolutionHandler };
        var rejectReaction = { capability: capability, handler: onRejected };
        switch (promise._status) {
          case 'unresolved':
            promise._resolveReactions.push(resolveReaction);
            promise._rejectReactions.push(rejectReaction);
            break;
          case 'has-resolution':
            triggerPromiseReactions([resolveReaction], promise._result);
            break;
          case 'has-rejection':
            triggerPromiseReactions([rejectReaction], promise._result);
            break;
          default:
            throw new TypeError('unexpected');
        }
        return capability.promise;
      }
    });
 
    return Promise;
  }());
 
  // Chrome's native Promise has extra methods that it shouldn't have. Let's remove them.
  Eif (globals.Promise) {
    delete globals.Promise.accept;
    delete globals.Promise.defer;
    delete globals.Promise.prototype.chain;
  }
 
  // export the Promise constructor.
  defineProperties(globals, { Promise: PromiseShim });
  // In Chrome 33 (and thereabouts) Promise is defined, but the
  // implementation is buggy in a number of ways.  Let's check subclassing
  // support to see if we have a buggy implementation.
  var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function (S) {
    return S.resolve(42) instanceof S;
  });
  var promiseIgnoresNonFunctionThenCallbacks = (function () {
    try {
      globals.Promise.reject(42).then(null, 5).then(null, function () {});
      return true;
    } catch (ex) {
      return false;
    }
  }());
  var promiseRequiresObjectContext = (function () {
    try { Promise.call(3, function () {}); } catch (e) { return true; }
    return false;
  }());
  Eif (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks || !promiseRequiresObjectContext) {
    /*globals Promise: true */
    Promise = PromiseShim;
    /*globals Promise: false */
    defineProperty(globals, 'Promise', PromiseShim, true);
  }
 
  // Map and Set require a true ES5 environment
  // Their fast path also requires that the environment preserve
  // property insertion order, which is not guaranteed by the spec.
  var testOrder = function (a) {
    var b = Object.keys(a.reduce(function (o, k) {
      o[k] = true;
      return o;
    }, {}));
    return a.join(':') === b.join(':');
  };
  var preservesInsertionOrder = testOrder(['z', 'a', 'bb']);
  // some engines (eg, Chrome) only preserve insertion order for string keys
  var preservesNumericInsertionOrder = testOrder(['z', 1, 'a', '3', 2]);
 
  Eif (supportsDescriptors) {
 
    var fastkey = function fastkey(key) {
      if (!preservesInsertionOrder) {
        return null;
      }
      var type = typeof key;
      if (type === 'string') {
        return '$' + key;
      } else if (type === 'number') {
        // note that -0 will get coerced to "0" when used as a property key
        if (!preservesNumericInsertionOrder) {
          return 'n' + key;
        }
        return key;
      }
      return null;
    };
 
    var emptyObject = function emptyObject() {
      // accomodate some older not-quite-ES5 browsers
      return Object.create ? Object.create(null) : {};
    };
 
    var collectionShims = {
      Map: (function () {
 
        var empty = {};
 
        function MapEntry(key, value) {
          this.key = key;
          this.value = value;
          this.next = null;
          this.prev = null;
        }
 
        MapEntry.prototype.isRemoved = function () {
          return this.key === empty;
        };
 
        function MapIterator(map, kind) {
          this.head = map._head;
          this.i = this.head;
          this.kind = kind;
        }
 
        MapIterator.prototype = {
          next: function () {
            var i = this.i, kind = this.kind, head = this.head, result;
            if (typeof this.i === 'undefined') {
              return { value: void 0, done: true };
            }
            while (i.isRemoved() && i !== head) {
              // back up off of removed entries
              i = i.prev;
            }
            // advance to next unreturned element.
            while (i.next !== head) {
              i = i.next;
              if (!i.isRemoved()) {
                if (kind === 'key') {
                  result = i.key;
                } else if (kind === 'value') {
                  result = i.value;
                } else {
                  result = [i.key, i.value];
                }
                this.i = i;
                return { value: result, done: false };
              }
            }
            // once the iterator is done, it is done forever.
            this.i = void 0;
            return { value: void 0, done: true };
          }
        };
        addIterator(MapIterator.prototype);
 
        function Map(iterable) {
          var map = this;
          Iif (!ES.TypeIsObject(map)) {
            throw new TypeError('Map does not accept arguments when called as a function');
          }
          map = emulateES6construct(map);
          Iif (!map._es6map) {
            throw new TypeError('bad map');
          }
 
          var head = new MapEntry(null, null);
          // circular doubly-linked list.
          head.next = head.prev = head;
 
          defineProperties(map, {
            _head: head,
            _storage: emptyObject(),
            _size: 0
          });
 
          // Optionally initialize map from iterable
          Iif (typeof iterable !== 'undefined' && iterable !== null) {
            var it = ES.GetIterator(iterable);
            var adder = map.set;
            if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); }
            while (true) {
              var next = ES.IteratorNext(it);
              if (next.done) { break; }
              var nextItem = next.value;
              if (!ES.TypeIsObject(nextItem)) {
                throw new TypeError('expected iterable of pairs');
              }
              adder.call(map, nextItem[0], nextItem[1]);
            }
          }
          return map;
        }
        var Map$prototype = Map.prototype;
        defineProperties(Map, {
          '@@create': function (obj) {
            var constructor = this;
            var prototype = constructor.prototype || Map$prototype;
            obj = obj || create(prototype);
            defineProperties(obj, { _es6map: true });
            return obj;
          }
        });
 
        Object.defineProperty(Map.prototype, 'size', {
          configurable: true,
          enumerable: false,
          get: function () {
            if (typeof this._size === 'undefined') {
              throw new TypeError('size method called on incompatible Map');
            }
            return this._size;
          }
        });
 
        defineProperties(Map.prototype, {
          get: function (key) {
            var fkey = fastkey(key);
            if (fkey !== null) {
              // fast O(1) path
              var entry = this._storage[fkey];
              if (entry) {
                return entry.value;
              } else {
                return;
              }
            }
            var head = this._head, i = head;
            while ((i = i.next) !== head) {
              if (ES.SameValueZero(i.key, key)) {
                return i.value;
              }
            }
            return;
          },
 
          has: function (key) {
            var fkey = fastkey(key);
            if (fkey !== null) {
              // fast O(1) path
              return typeof this._storage[fkey] !== 'undefined';
            }
            var head = this._head, i = head;
            while ((i = i.next) !== head) {
              if (ES.SameValueZero(i.key, key)) {
                return true;
              }
            }
            return false;
          },
 
          set: function (key, value) {
            var head = this._head, i = head, entry;
            var fkey = fastkey(key);
            if (fkey !== null) {
              // fast O(1) path
              if (typeof this._storage[fkey] !== 'undefined') {
                this._storage[fkey].value = value;
                return this;
              } else {
                entry = this._storage[fkey] = new MapEntry(key, value);
                i = head.prev;
                // fall through
              }
            }
            while ((i = i.next) !== head) {
              if (ES.SameValueZero(i.key, key)) {
                i.value = value;
                return this;
              }
            }
            entry = entry || new MapEntry(key, value);
            if (ES.SameValue(-0, key)) {
              entry.key = +0; // coerce -0 to +0 in entry
            }
            entry.next = this._head;
            entry.prev = this._head.prev;
            entry.prev.next = entry;
            entry.next.prev = entry;
            this._size += 1;
            return this;
          },
 
          'delete': function (key) {
            var head = this._head, i = head;
            var fkey = fastkey(key);
            if (fkey !== null) {
              // fast O(1) path
              if (typeof this._storage[fkey] === 'undefined') {
                return false;
              }
              i = this._storage[fkey].prev;
              delete this._storage[fkey];
              // fall through
            }
            while ((i = i.next) !== head) {
              if (ES.SameValueZero(i.key, key)) {
                i.key = i.value = empty;
                i.prev.next = i.next;
                i.next.prev = i.prev;
                this._size -= 1;
                return true;
              }
            }
            return false;
          },
 
          clear: function () {
            this._size = 0;
            this._storage = emptyObject();
            var head = this._head, i = head, p = i.next;
            while ((i = p) !== head) {
              i.key = i.value = empty;
              p = i.next;
              i.next = i.prev = head;
            }
            head.next = head.prev = head;
          },
 
          keys: function () {
            return new MapIterator(this, 'key');
          },
 
          values: function () {
            return new MapIterator(this, 'value');
          },
 
          entries: function () {
            return new MapIterator(this, 'key+value');
          },
 
          forEach: function (callback) {
            var context = arguments.length > 1 ? arguments[1] : null;
            var it = this.entries();
            for (var entry = it.next(); !entry.done; entry = it.next()) {
              if (context) {
                callback.call(context, entry.value[1], entry.value[0], this);
              } else {
                callback(entry.value[1], entry.value[0], this);
              }
            }
          }
        });
        addIterator(Map.prototype, function () { return this.entries(); });
 
        return Map;
      })(),
 
      Set: (function () {
        // Creating a Map is expensive.  To speed up the common case of
        // Sets containing only string or numeric keys, we use an object
        // as backing storage and lazily create a full Map only when
        // required.
        var SetShim = function Set(iterable) {
          var set = this;
          Iif (!ES.TypeIsObject(set)) {
            throw new TypeError('Set does not accept arguments when called as a function');
          }
          set = emulateES6construct(set);
          Iif (!set._es6set) {
            throw new TypeError('bad set');
          }
 
          defineProperties(set, {
            '[[SetData]]': null,
            _storage: emptyObject()
          });
 
          // Optionally initialize map from iterable
          Iif (typeof iterable !== 'undefined' && iterable !== null) {
            var it = ES.GetIterator(iterable);
            var adder = set.add;
            if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); }
            while (true) {
              var next = ES.IteratorNext(it);
              if (next.done) { break; }
              var nextItem = next.value;
              adder.call(set, nextItem);
            }
          }
          return set;
        };
        var Set$prototype = SetShim.prototype;
        defineProperties(SetShim, {
          '@@create': function (obj) {
            var constructor = this;
            var prototype = constructor.prototype || Set$prototype;
            obj = obj || create(prototype);
            defineProperties(obj, { _es6set: true });
            return obj;
          }
        });
 
        // Switch from the object backing storage to a full Map.
        var ensureMap = function ensureMap(set) {
          Eif (!set['[[SetData]]']) {
            var m = set['[[SetData]]'] = new collectionShims.Map();
            Object.keys(set._storage).forEach(function (k) {
              // fast check for leading '$'
              if (k.charCodeAt(0) === 36) {
                k = k.slice(1);
              } else if (k.charAt(0) === 'n') {
                k = +k.slice(1);
              } else {
                k = +k;
              }
              m.set(k, k);
            });
            set._storage = null; // free old backing storage
          }
        };
 
        Object.defineProperty(SetShim.prototype, 'size', {
          configurable: true,
          enumerable: false,
          get: function () {
            if (typeof this._storage === 'undefined') {
              // https://github.com/paulmillr/es6-shim/issues/176
              throw new TypeError('size method called on incompatible Set');
            }
            ensureMap(this);
            return this['[[SetData]]'].size;
          }
        });
 
        defineProperties(SetShim.prototype, {
          has: function (key) {
            var fkey;
            if (this._storage && (fkey = fastkey(key)) !== null) {
              return !!this._storage[fkey];
            }
            ensureMap(this);
            return this['[[SetData]]'].has(key);
          },
 
          add: function (key) {
            var fkey;
            if (this._storage && (fkey = fastkey(key)) !== null) {
              this._storage[fkey] = true;
              return this;
            }
            ensureMap(this);
            this['[[SetData]]'].set(key, key);
            return this;
          },
 
          'delete': function (key) {
            var fkey;
            if (this._storage && (fkey = fastkey(key)) !== null) {
              var hasFKey = _hasOwnProperty(this._storage, fkey);
              return (delete this._storage[fkey]) && hasFKey;
            }
            ensureMap(this);
            return this['[[SetData]]']['delete'](key);
          },
 
          clear: function () {
            if (this._storage) {
              this._storage = emptyObject();
              return;
            }
            return this['[[SetData]]'].clear();
          },
 
          values: function () {
            ensureMap(this);
            return this['[[SetData]]'].values();
          },
 
          entries: function () {
            ensureMap(this);
            return this['[[SetData]]'].entries();
          },
 
          forEach: function (callback) {
            var context = arguments.length > 1 ? arguments[1] : null;
            var entireSet = this;
            ensureMap(entireSet);
            this['[[SetData]]'].forEach(function (value, key) {
              if (context) {
                callback.call(context, key, key, entireSet);
              } else {
                callback(key, key, entireSet);
              }
            });
          }
        });
        defineProperty(SetShim, 'keys', SetShim.values, true);
        addIterator(SetShim.prototype, function () { return this.values(); });
 
        return SetShim;
      })()
    };
    defineProperties(globals, collectionShims);
 
    Eif (globals.Map || globals.Set) {
      /*
        - In Firefox < 23, Map#size is a function.
        - In all current Firefox, Set#entries/keys/values & Map#clear do not exist
        - https://bugzilla.mozilla.org/show_bug.cgi?id=869996
        - In Firefox 24, Map and Set do not implement forEach
        - In Firefox 25 at least, Map and Set are callable without "new"
      */
      Eif (
        typeof globals.Map.prototype.clear !== 'function' ||
        new globals.Set().size !== 0 ||
        new globals.Map().size !== 0 ||
        typeof globals.Map.prototype.keys !== 'function' ||
        typeof globals.Set.prototype.keys !== 'function' ||
        typeof globals.Map.prototype.forEach !== 'function' ||
        typeof globals.Set.prototype.forEach !== 'function' ||
        isCallableWithoutNew(globals.Map) ||
        isCallableWithoutNew(globals.Set) ||
        !supportsSubclassing(globals.Map, function (M) {
          var m = new M([]);
          // Firefox 32 is ok with the instantiating the subclass but will
          // throw when the map is used.
          m.set(42, 42);
          return m instanceof M;
        })
      ) {
        globals.Map = collectionShims.Map;
        globals.Set = collectionShims.Set;
      }
    }
    Eif (globals.Set.prototype.keys !== globals.Set.prototype.values) {
      defineProperty(globals.Set.prototype, 'keys', globals.Set.prototype.values, true);
    }
    // Shim incomplete iterator implementations.
    addIterator(Object.getPrototypeOf((new globals.Map()).keys()));
    addIterator(Object.getPrototypeOf((new globals.Set()).keys()));
  }
 
  return globals;
}));
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4  1    
 
module.exports = require('./lib/express');
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/

Statements: 20.82% (157 / 754)      Branches: 0% (0 / 354)      Functions: 2.97% (3 / 101)      Lines: 22.11% (157 / 710)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/lib/
File Statements Branches Functions Lines
application.js 19.3% (33 / 171) 0% (0 / 64) 4% (1 / 25) 20% (33 / 165)
express.js 65.38% (17 / 26) 100% (0 / 0) 25% (1 / 4) 65.38% (17 / 26)
request.js 29.81% (31 / 104) 0% (0 / 58) 4.76% (1 / 21) 32.29% (31 / 96)
response.js 14.19% (44 / 310) 0% (0 / 162) 0% (0 / 33) 15.22% (44 / 289)
utils.js 19.1% (17 / 89) 0% (0 / 48) 0% (0 / 13) 20.73% (17 / 82)
view.js 27.78% (15 / 54) 0% (0 / 22) 0% (0 / 5) 28.85% (15 / 52)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/application.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/application.js

Statements: 19.3% (33 / 171)      Branches: 0% (0 / 64)      Functions: 4% (1 / 25)      Lines: 20% (33 / 165)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559        1 1 1 1 1 1 1 1 1 1 1 1 1           1                       1                                                             1                                                                                               1                                                                           1                                                                                                                                   1                                                                           1                                     1                                                     1                                                                                   1                                         1                                     1                       1                       1               1 33                                     1                                                     1                                                                                                                                                               1                       1        
/**
 * Module dependencies.
 */
 
var finalhandler = require('finalhandler');
var flatten = require('./utils').flatten;
var Router = require('./router');
var methods = require('methods');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var merge = require('utils-merge');
var resolve = require('path').resolve;
var slice = Array.prototype.slice;
 
/**
 * Application prototype.
 */
 
var app = exports = module.exports = {};
 
/**
 * Initialize the server.
 *
 *   - setup default configuration
 *   - setup default middleware
 *   - setup route reflection methods
 *
 * @api private
 */
 
app.init = function(){
  var router = null;
 
  this.cache = {};
  this.settings = {};
  this.engines = {};
  this.defaultConfiguration();
 
  // Setup getting to lazily add base router
  Object.defineProperty(this, 'router', {
    configurable: true,
    enumerable: true,
    get: function getrouter() {
      if (router === null) {
        router = new Router({
          caseSensitive: this.enabled('case sensitive routing'),
          strict: this.enabled('strict routing')
        });
      }
 
      return router;
    }
  });
};
 
/**
 * Initialize application configuration.
 *
 * @api private
 */
 
app.defaultConfiguration = function(){
  // default settings
  this.enable('x-powered-by');
  this.set('etag', 'weak');
  var env = process.env.NODE_ENV || 'development';
  this.set('env', env);
  this.set('query parser', 'extended');
  this.set('subdomain offset', 2);
  this.set('trust proxy', false);
 
  debug('booting in %s mode', env);
 
  // inherit protos
  this.on('mount', function(parent){
    this.request.__proto__ = parent.request;
    this.response.__proto__ = parent.response;
    this.engines.__proto__ = parent.engines;
    this.settings.__proto__ = parent.settings;
  });
 
  // setup locals
  this.locals = Object.create(null);
 
  // top-most app is mounted at /
  this.mountpath = '/';
 
  // default locals
  this.locals.settings = this.settings;
 
  // default configuration
  this.set('view', View);
  this.set('views', resolve('views'));
  this.set('jsonp callback name', 'callback');
 
  if (env === 'production') {
    this.enable('view cache');
  }
};
 
/**
 * Dispatch a req, res pair into the application. Starts pipeline processing.
 *
 * If no _done_ callback is provided, then default error handlers will respond
 * in the event of an error bubbling through the stack.
 *
 * @api private
 */
 
app.handle = function(req, res, done) {
  // final handler
  done = done || finalhandler(req, res, {
    env: this.get('env'),
    onerror: logerror.bind(this)
  });
 
  // set powered by header
  if (this.enabled('x-powered-by')) {
    res.setHeader('X-Powered-By', 'Express');
  }
 
  // set circular references
  req.res = res;
  res.req = req;
 
  // alter the prototypes
  req.__proto__ = this.request;
  res.__proto__ = this.response;
 
  // setup locals
  if (!res.locals) {
    res.locals = Object.create(null);
  }
 
  this.router.handle(req, res, done);
};
 
/**
 * Proxy `Router#use()` to add middleware to the app router.
 * See Router#use() documentation for details.
 *
 * If the _fn_ parameter is an express app, then it will be
 * mounted at the _route_ specified.
 *
 * @api public
 */
 
app.use = function use(fn) {
  var offset = 0;
  var path = '/';
 
  // default path to '/'
  // disambiguate app.use([fn])
  if (typeof fn !== 'function') {
    var arg = fn;
 
    while (Array.isArray(arg) && arg.length !== 0) {
      arg = arg[0];
    }
 
    // first arg is the path
    if (typeof arg !== 'function') {
      offset = 1;
      path = fn;
    }
  }
 
  var fns = flatten(slice.call(arguments, offset));
 
  if (fns.length === 0) {
    throw new TypeError('app.use() requires middleware functions');
  }
 
  // get router
  var router = this.router;
 
  fns.forEach(function (fn) {
    // non-express app
    if (!fn || !fn.handle || !fn.set) {
      return router.use(path, fn);
    }
 
    debug('.use app under %s', path);
    fn.mountpath = path;
    fn.parent = this;
 
    // restore .app property on req and res
    router.use(path, function mounted_app(req, res, next) {
      var orig = req.app;
      fn.handle(req, res, function (err) {
        req.__proto__ = orig.request;
        res.__proto__ = orig.response;
        next(err);
      });
    });
 
    // mounted an app
    fn.emit('mount', this);
  }, this);
 
  return this;
};
 
/**
 * Proxy to the app `Router#route()`
 * Returns a new `Route` instance for the _path_.
 *
 * Routes are isolated middleware stacks for specific paths.
 * See the Route api docs for details.
 *
 * @api public
 */
 
app.route = function route(path) {
  return this.router.route(path);
};
 
/**
 * Register the given template engine callback `fn`
 * as `ext`.
 *
 * By default will `require()` the engine based on the
 * file extension. For example if you try to render
 * a "foo.jade" file Express will invoke the following internally:
 *
 *     app.engine('jade', require('jade').__express);
 *
 * For engines that do not provide `.__express` out of the box,
 * or if you wish to "map" a different extension to the template engine
 * you may use this method. For example mapping the EJS template engine to
 * ".html" files:
 *
 *     app.engine('html', require('ejs').renderFile);
 *
 * In this case EJS provides a `.renderFile()` method with
 * the same signature that Express expects: `(path, options, callback)`,
 * though note that it aliases this method as `ejs.__express` internally
 * so if you're using ".ejs" extensions you dont need to do anything.
 *
 * Some template engines do not follow this convention, the
 * [Consolidate.js](https://github.com/tj/consolidate.js)
 * library was created to map all of node's popular template
 * engines to follow this convention, thus allowing them to
 * work seamlessly within Express.
 *
 * @param {String} ext
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */
 
app.engine = function(ext, fn){
  if ('function' != typeof fn) throw new Error('callback function required');
  if ('.' != ext[0]) ext = '.' + ext;
  this.engines[ext] = fn;
  return this;
};
 
/**
 * Proxy to `Router#param()` with one added api feature. The _name_ parameter
 * can be an array of names.
 *
 * See the Router#param() docs for more details.
 *
 * @param {String|Array} name
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */
 
app.param = function param(name, fn) {
  if (Array.isArray(name)) {
    for (var i = 0; i < name.length; i++) {
      this.param(name[i], fn);
    }
    return this;
  }
 
  this.router.param(name, fn);
  return this;
};
 
/**
 * Assign `setting` to `val`, or return `setting`'s value.
 *
 *    app.set('foo', 'bar');
 *    app.get('foo');
 *    // => "bar"
 *
 * Mounted servers inherit their parent server's settings.
 *
 * @param {String} setting
 * @param {*} [val]
 * @return {Server} for chaining
 * @api public
 */
 
app.set = function(setting, val){
  if (arguments.length === 1) {
    // app.get(setting)
    return this.settings[setting];
  }
 
  // set value
  this.settings[setting] = val;
 
  // trigger matched settings
  switch (setting) {
    case 'etag':
      debug('compile etag %s', val);
      this.set('etag fn', compileETag(val));
      break;
    case 'query parser':
      debug('compile query parser %s', val);
      this.set('query parser fn', compileQueryParser(val));
      break;
    case 'trust proxy':
      debug('compile trust proxy %s', val);
      this.set('trust proxy fn', compileTrust(val));
      break;
  }
 
  return this;
};
 
/**
 * Return the app's absolute pathname
 * based on the parent(s) that have
 * mounted it.
 *
 * For example if the application was
 * mounted as "/admin", which itself
 * was mounted as "/blog" then the
 * return value would be "/blog/admin".
 *
 * @return {String}
 * @api private
 */
 
app.path = function(){
  return this.parent
    ? this.parent.path() + this.mountpath
    : '';
};
 
/**
 * Check if `setting` is enabled (truthy).
 *
 *    app.enabled('foo')
 *    // => false
 *
 *    app.enable('foo')
 *    app.enabled('foo')
 *    // => true
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */
 
app.enabled = function(setting){
  return !!this.set(setting);
};
 
/**
 * Check if `setting` is disabled.
 *
 *    app.disabled('foo')
 *    // => true
 *
 *    app.enable('foo')
 *    app.disabled('foo')
 *    // => false
 *
 * @param {String} setting
 * @return {Boolean}
 * @api public
 */
 
app.disabled = function(setting){
  return !this.set(setting);
};
 
/**
 * Enable `setting`.
 *
 * @param {String} setting
 * @return {app} for chaining
 * @api public
 */
 
app.enable = function(setting){
  return this.set(setting, true);
};
 
/**
 * Disable `setting`.
 *
 * @param {String} setting
 * @return {app} for chaining
 * @api public
 */
 
app.disable = function(setting){
  return this.set(setting, false);
};
 
/**
 * Delegate `.VERB(...)` calls to `router.VERB(...)`.
 */
 
methods.forEach(function(method){
  app[method] = function(path){
    if ('get' == method && 1 == arguments.length) return this.set(path);
 
    var route = this.route(path);
    route[method].apply(route, slice.call(arguments, 1));
    return this;
  };
});
 
/**
 * Special-cased "all" method, applying the given route `path`,
 * middleware, and callback to _every_ HTTP method.
 *
 * @param {String} path
 * @param {Function} ...
 * @return {app} for chaining
 * @api public
 */
 
app.all = function(path){
  var route = this.route(path);
  var args = slice.call(arguments, 1);
  methods.forEach(function(method){
    route[method].apply(route, args);
  });
 
  return this;
};
 
/**
 * Render the given view `name` name with `options`
 * and a callback accepting an error and the
 * rendered template string.
 *
 * Example:
 *
 *    app.render('email', { name: 'Tobi' }, function(err, html){
 *      // ...
 *    })
 *
 * @param {String} name
 * @param {String|Function} options or fn
 * @param {Function} fn
 * @api public
 */
 
app.render = function(name, options, fn){
  var opts = {};
  var cache = this.cache;
  var engines = this.engines;
  var view;
 
  // support callback function as second arg
  if ('function' == typeof options) {
    fn = options, options = {};
  }
 
  // merge app.locals
  merge(opts, this.locals);
 
  // merge options._locals
  if (options._locals) {
    merge(opts, options._locals);
  }
 
  // merge options
  merge(opts, options);
 
  // set .cache unless explicitly provided
  opts.cache = null == opts.cache
    ? this.enabled('view cache')
    : opts.cache;
 
  // primed cache
  if (opts.cache) view = cache[name];
 
  // view
  if (!view) {
    view = new (this.get('view'))(name, {
      defaultEngine: this.get('view engine'),
      root: this.get('views'),
      engines: engines
    });
 
    if (!view.path) {
      var dirs = Array.isArray(view.root) && view.root.length > 1
        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
        : 'directory "' + view.root + '"'
      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
      err.view = view;
      return fn(err);
    }
 
    // prime the cache
    if (opts.cache) cache[name] = view;
  }
 
  // render
  try {
    view.render(opts, fn);
  } catch (err) {
    fn(err);
  }
};
 
/**
 * Listen for connections.
 *
 * A node `http.Server` is returned, with this
 * application (which is a `Function`) as its
 * callback. If you wish to create both an HTTP
 * and HTTPS server you may do so with the "http"
 * and "https" modules as shown here:
 *
 *    var http = require('http')
 *      , https = require('https')
 *      , express = require('express')
 *      , app = express();
 *
 *    http.createServer(app).listen(80);
 *    https.createServer({ ... }, app).listen(443);
 *
 * @return {http.Server}
 * @api public
 */
 
app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};
 
/**
* Log error using console.error.
*
* @param {Error} err
* @api public
*/
 
function logerror(err){
  if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/express.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/express.js

Statements: 65.38% (17 / 26)      Branches: 100% (0 / 0)      Functions: 25% (1 / 4)      Lines: 65.38% (17 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95        1 1 1 1 1 1 1           1                 1                                   1 1 1           1 1           1           1                                           20                
/**
 * Module dependencies.
 */
 
var EventEmitter = require('events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./application');
var Route = require('./router/route');
var Router = require('./router');
var req = require('./request');
var res = require('./response');
 
/**
 * Expose `createApplication()`.
 */
 
exports = module.exports = createApplication;
 
/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */
 
function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };
 
  mixin(app, proto);
  mixin(app, EventEmitter.prototype);
 
  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
}
 
/**
 * Expose the prototypes.
 */
 
exports.application = proto;
exports.request = req;
exports.response = res;
 
/**
 * Expose constructors.
 */
 
exports.Route = Route;
exports.Router = Router;
 
/**
 * Expose middleware
 */
 
exports.static = require('serve-static');
 
/**
 * Replace removed middleware with an appropriate error message.
 */
 
[
  'json',
  'urlencoded',
  'bodyParser',
  'compress',
  'cookieSession',
  'session',
  'logger',
  'cookieParser',
  'favicon',
  'responseTime',
  'errorHandler',
  'timeout',
  'methodOverride',
  'vhost',
  'csrf',
  'directory',
  'limit',
  'multipart',
  'staticCache',
  'query',
].forEach(function (name) {
  Object.defineProperty(exports, name, {
    get: function () {
      throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.');
    },
    configurable: true
  });
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/request.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/request.js

Statements: 29.81% (31 / 104)      Branches: 0% (0 / 58)      Functions: 4.76% (1 / 21)      Lines: 32.29% (31 / 96)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486        1 1 1 1 1 1 1 1           1                                                       1                                                                                                                   1                         1                           1                           1                                                 1                               1                                                           1                                                                       1                                     1                                                 1                           1                                 1                                         1                                       1                             1                                           1                                                 1                                               1                     1                         1 12              
/**
 * Module dependencies.
 */
 
var accepts = require('accepts');
var isIP = require('net').isIP;
var typeis = require('type-is');
var http = require('http');
var fresh = require('fresh');
var parseRange = require('range-parser');
var parse = require('parseurl');
var proxyaddr = require('proxy-addr');
 
/**
 * Request prototype.
 */
 
var req = exports = module.exports = {
  __proto__: http.IncomingMessage.prototype
};
 
/**
 * Return request header.
 *
 * The `Referrer` header field is special-cased,
 * both `Referrer` and `Referer` are interchangeable.
 *
 * Examples:
 *
 *     req.get('Content-Type');
 *     // => "text/plain"
 *
 *     req.get('content-type');
 *     // => "text/plain"
 *
 *     req.get('Something');
 *     // => undefined
 *
 * Aliased as `req.header()`.
 *
 * @param {String} name
 * @return {String}
 * @api public
 */
 
req.get =
req.header = function(name){
  switch (name = name.toLowerCase()) {
    case 'referer':
    case 'referrer':
      return this.headers.referrer
        || this.headers.referer;
    default:
      return this.headers[name];
  }
};
 
/**
 * To do: update docs.
 *
 * Check if the given `type(s)` is acceptable, returning
 * the best match when true, otherwise `undefined`, in which
 * case you should respond with 406 "Not Acceptable".
 *
 * The `type` value may be a single mime type string
 * such as "application/json", the extension name
 * such as "json", a comma-delimted list such as "json, html, text/plain",
 * an argument list such as `"json", "html", "text/plain"`,
 * or an array `["json", "html", "text/plain"]`. When a list
 * or array is given the _best_ match, if any is returned.
 *
 * Examples:
 *
 *     // Accept: text/html
 *     req.accepts('html');
 *     // => "html"
 *
 *     // Accept: text/*, application/json
 *     req.accepts('html');
 *     // => "html"
 *     req.accepts('text/html');
 *     // => "text/html"
 *     req.accepts('json, text');
 *     // => "json"
 *     req.accepts('application/json');
 *     // => "application/json"
 *
 *     // Accept: text/*, application/json
 *     req.accepts('image/png');
 *     req.accepts('png');
 *     // => undefined
 *
 *     // Accept: text/*;q=.5, application/json
 *     req.accepts(['html', 'json']);
 *     req.accepts('html', 'json');
 *     req.accepts('html, json');
 *     // => "json"
 *
 * @param {String|Array} type(s)
 * @return {String}
 * @api public
 */
 
req.accepts = function(){
  var accept = accepts(this);
  return accept.types.apply(accept, arguments);
};
 
/**
 * Check if the given `encoding`s are accepted.
 *
 * @param {String} ...encoding
 * @return {Boolean}
 * @api public
 */
 
req.acceptsEncodings = function(){
  var accept = accepts(this);
  return accept.encodings.apply(accept, arguments);
};
 
/**
 * Check if the given `charset`s are acceptable,
 * otherwise you should respond with 406 "Not Acceptable".
 *
 * @param {String} ...charset
 * @return {Boolean}
 * @api public
 */
 
req.acceptsCharsets = function(){
  var accept = accepts(this);
  return accept.charsets.apply(accept, arguments);
};
 
/**
 * Check if the given `lang`s are acceptable,
 * otherwise you should respond with 406 "Not Acceptable".
 *
 * @param {String} ...lang
 * @return {Boolean}
 * @api public
 */
 
req.acceptsLanguages = function(){
  var accept = accepts(this);
  return accept.languages.apply(accept, arguments);
};
 
/**
 * Parse Range header field,
 * capping to the given `size`.
 *
 * Unspecified ranges such as "0-" require
 * knowledge of your resource length. In
 * the case of a byte range this is of course
 * the total number of bytes. If the Range
 * header field is not given `null` is returned,
 * `-1` when unsatisfiable, `-2` when syntactically invalid.
 *
 * NOTE: remember that ranges are inclusive, so
 * for example "Range: users=0-3" should respond
 * with 4 users when available, not 3.
 *
 * @param {Number} size
 * @return {Array}
 * @api public
 */
 
req.range = function(size){
  var range = this.get('Range');
  if (!range) return;
  return parseRange(size, range);
};
 
/**
 * Parse the query string of `req.url`.
 *
 * This uses the "query parser" setting to parse the raw
 * string into an object.
 *
 * @return {String}
 * @api public
 */
 
defineGetter(req, 'query', function query(){
  var queryparse = this.app.get('query parser fn');
 
  if (!queryparse) {
    // parsing is disabled
    return Object.create(null);
  }
 
  var querystring = parse(this).query;
 
  return queryparse(querystring);
});
 
/**
 * Return the value of param `name` when present or `defaultValue`.
 *
 *  - Checks route placeholders, ex: _/user/:id_
 *  - Checks body params, ex: id=12, {"id":12}
 *  - Checks query string params, ex: ?id=12
 *
 * To utilize request bodies, `req.body`
 * should be an object. This can be done by using
 * the `bodyParser()` middleware.
 *
 * @param {String} name
 * @param {Mixed} [defaultValue]
 * @return {String}
 * @api public
 */
 
req.param = function(name, defaultValue){
  var params = this.params || {};
  var body = this.body || {};
  var query = this.query || {};
  if (null != params[name] && params.hasOwnProperty(name)) return params[name];
  if (null != body[name]) return body[name];
  if (null != query[name]) return query[name];
  return defaultValue;
};
 
/**
 * Check if the incoming request contains the "Content-Type"
 * header field, and it contains the give mime `type`.
 *
 * Examples:
 *
 *      // With Content-Type: text/html; charset=utf-8
 *      req.is('html');
 *      req.is('text/html');
 *      req.is('text/*');
 *      // => true
 *
 *      // When Content-Type is application/json
 *      req.is('json');
 *      req.is('application/json');
 *      req.is('application/*');
 *      // => true
 *
 *      req.is('html');
 *      // => false
 *
 * @param {String} type
 * @return {Boolean}
 * @api public
 */
 
req.is = function(types){
  if (!Array.isArray(types)) types = [].slice.call(arguments);
  return typeis(this, types);
};
 
/**
 * Return the protocol string "http" or "https"
 * when requested with TLS. When the "trust proxy"
 * setting trusts the socket address, the
 * "X-Forwarded-Proto" header field will be trusted
 * and used if present.
 *
 * If you're running behind a reverse proxy that
 * supplies https for you this may be enabled.
 *
 * @return {String}
 * @api public
 */
 
defineGetter(req, 'protocol', function protocol(){
  var proto = this.connection.encrypted
    ? 'https'
    : 'http';
  var trust = this.app.get('trust proxy fn');
 
  if (!trust(this.connection.remoteAddress)) {
    return proto;
  }
 
  // Note: X-Forwarded-Proto is normally only ever a
  //       single value, but this is to be safe.
  proto = this.get('X-Forwarded-Proto') || proto;
  return proto.split(/\s*,\s*/)[0];
});
 
/**
 * Short-hand for:
 *
 *    req.protocol == 'https'
 *
 * @return {Boolean}
 * @api public
 */
 
defineGetter(req, 'secure', function secure(){
  return 'https' == this.protocol;
});
 
/**
 * Return the remote address from the trusted proxy.
 *
 * The is the remote address on the socket unless
 * "trust proxy" is set.
 *
 * @return {String}
 * @api public
 */
 
defineGetter(req, 'ip', function ip(){
  var trust = this.app.get('trust proxy fn');
  return proxyaddr(this, trust);
});
 
/**
 * When "trust proxy" is set, trusted proxy addresses + client.
 *
 * For example if the value were "client, proxy1, proxy2"
 * you would receive the array `["client", "proxy1", "proxy2"]`
 * where "proxy2" is the furthest down-stream and "proxy1" and
 * "proxy2" were trusted.
 *
 * @return {Array}
 * @api public
 */
 
defineGetter(req, 'ips', function ips() {
  var trust = this.app.get('trust proxy fn');
  var addrs = proxyaddr.all(this, trust);
  return addrs.slice(1).reverse();
});
 
/**
 * Return subdomains as an array.
 *
 * Subdomains are the dot-separated parts of the host before the main domain of
 * the app. By default, the domain of the app is assumed to be the last two
 * parts of the host. This can be changed by setting "subdomain offset".
 *
 * For example, if the domain is "tobi.ferrets.example.com":
 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
 *
 * @return {Array}
 * @api public
 */
 
defineGetter(req, 'subdomains', function subdomains() {
  var hostname = this.hostname;
 
  if (!hostname) return [];
 
  var offset = this.app.get('subdomain offset');
  var subdomains = !isIP(hostname)
    ? hostname.split('.').reverse()
    : [hostname];
 
  return subdomains.slice(offset);
});
 
/**
 * Short-hand for `url.parse(req.url).pathname`.
 *
 * @return {String}
 * @api public
 */
 
defineGetter(req, 'path', function path() {
  return parse(this).pathname;
});
 
/**
 * Parse the "Host" header field to a host.
 *
 * When the "trust proxy" setting trusts the socket
 * address, the "X-Forwarded-Host" header field will
 * be trusted.
 *
 * @return {String}
 * @api public
 */
 
defineGetter(req, 'host', function host(){
  var trust = this.app.get('trust proxy fn');
  var val = this.get('X-Forwarded-Host');
 
  if (!val || !trust(this.connection.remoteAddress)) {
    val = this.get('Host');
  }
 
  return val || undefined;
});
 
/**
 * Parse the "Host" header field to a hostname.
 *
 * When the "trust proxy" setting trusts the socket
 * address, the "X-Forwarded-Host" header field will
 * be trusted.
 *
 * @return {String}
 * @api public
 */
 
defineGetter(req, 'hostname', function hostname(){
  var host = this.host;
 
  if (!host) return;
 
  // IPv6 literal support
  var offset = host[0] === '['
    ? host.indexOf(']') + 1
    : 0;
  var index = host.indexOf(':', offset);
 
  return ~index
    ? host.substring(0, index)
    : host;
});
 
/**
 * Check if the request is fresh, aka
 * Last-Modified and/or the ETag
 * still match.
 *
 * @return {Boolean}
 * @api public
 */
 
defineGetter(req, 'fresh', function(){
  var method = this.method;
  var s = this.res.statusCode;
 
  // GET or HEAD for weak freshness validation only
  if ('GET' != method && 'HEAD' != method) return false;
 
  // 2xx or 304 as per rfc2616 14.26
  if ((s >= 200 && s < 300) || 304 == s) {
    return fresh(this.headers, this.res._headers);
  }
 
  return false;
});
 
/**
 * Check if the request is stale, aka
 * "Last-Modified" and / or the "ETag" for the
 * resource has changed.
 *
 * @return {Boolean}
 * @api public
 */
 
defineGetter(req, 'stale', function stale(){
  return !this.fresh;
});
 
/**
 * Check if the request was an _XMLHttpRequest_.
 *
 * @return {Boolean}
 * @api public
 */
 
defineGetter(req, 'xhr', function xhr(){
  var val = this.get('X-Requested-With') || '';
  return 'xmlhttprequest' == val.toLowerCase();
});
 
/**
 * Helper function for creating a getter on an object.
 *
 * @param {Object} obj
 * @param {String} name
 * @param {Function} getter
 * @api private
 */
function defineGetter(obj, name, getter) {
  Object.defineProperty(obj, name, {
    configurable: true,
    enumerable: true,
    get: getter
  });
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/response.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/response.js

Statements: 14.19% (44 / 310)      Branches: 0% (0 / 162)      Functions: 0% (0 / 33)      Lines: 15.22% (44 / 289)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871        1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1           1                       1                                       1                                         1                                                                                                                                                                                                                       1                                                                       1                                                                                                                                 1                                                                                                   1                                                                                                   1                                                                         1                                                                                                                               1                                                                     1                                                       1                                                   1                         1                                                             1                                                                                           1                                                         1                                                                                                               1                                                 1                                                 1       1                   1             1             1                                                                          
/**
 * Module dependencies.
 */
 
var contentDisposition = require('content-disposition');
var deprecate = require('depd')('express');
var escapeHtml = require('escape-html');
var http = require('http');
var isAbsolute = require('./utils').isAbsolute;
var onFinished = require('on-finished');
var path = require('path');
var merge = require('utils-merge');
var sign = require('cookie-signature').sign;
var normalizeType = require('./utils').normalizeType;
var normalizeTypes = require('./utils').normalizeTypes;
var setCharset = require('./utils').setCharset;
var statusCodes = http.STATUS_CODES;
var cookie = require('cookie');
var send = require('send');
var extname = path.extname;
var mime = send.mime;
var resolve = path.resolve;
var vary = require('vary');
 
/**
 * Response prototype.
 */
 
var res = module.exports = {
  __proto__: http.ServerResponse.prototype
};
 
/**
 * Set status `code`.
 *
 * @param {Number} code
 * @return {ServerResponse}
 * @api public
 */
 
res.status = function(code){
  this.statusCode = code;
  return this;
};
 
/**
 * Set Link header field with the given `links`.
 *
 * Examples:
 *
 *    res.links({
 *      next: 'http://api.example.com/users?page=2',
 *      last: 'http://api.example.com/users?page=5'
 *    });
 *
 * @param {Object} links
 * @return {ServerResponse}
 * @api public
 */
 
res.links = function(links){
  var link = this.get('Link') || '';
  if (link) link += ', ';
  return this.set('Link', link + Object.keys(links).map(function(rel){
    return '<' + links[rel] + '>; rel="' + rel + '"';
  }).join(', '));
};
 
/**
 * Send a response.
 *
 * Examples:
 *
 *     res.send(new Buffer('wahoo'));
 *     res.send({ some: 'json' });
 *     res.send('<p>some html</p>');
 *
 * @param {string|number|boolean|object|Buffer} body
 * @api public
 */
 
res.send = function send(body) {
  var chunk = body;
  var encoding;
  var len;
  var req = this.req;
  var type;
 
  // settings
  var app = this.app;
 
  // support res.send(status, body)
  if (arguments.length === 2) {
    deprecate('res.send(status, body): Use res.status(status).send(body) instead');
    this.statusCode = arguments[0];
    chunk = arguments[1];
  }
 
  switch (typeof chunk) {
    // string defaulting to html
    case 'string':
      if (!this.get('Content-Type')) {
        this.type('html');
      }
      break;
    case 'boolean':
    case 'number':
    case 'object':
      if (chunk === null) {
        chunk = '';
      } else if (Buffer.isBuffer(chunk)) {
        if (!this.get('Content-Type')) {
          this.type('bin');
        }
      } else {
        return this.json(chunk);
      }
      break;
  }
 
  // write strings in utf-8
  if (typeof chunk === 'string') {
    encoding = 'utf8';
    type = this.get('Content-Type');
 
    // reflect this in content-type
    if (typeof type === 'string') {
      this.set('Content-Type', setCharset(type, 'utf-8'));
    }
  }
 
  // populate Content-Length
  if (chunk !== undefined) {
    if (!Buffer.isBuffer(chunk)) {
      // convert chunk to Buffer; saves later double conversions
      chunk = new Buffer(chunk, encoding);
      encoding = undefined;
    }
 
    len = chunk.length;
    this.set('Content-Length', len);
  }
 
  // method check
  var isHead = req.method === 'HEAD';
 
  // ETag support
  if (len !== undefined && (isHead || req.method === 'GET')) {
    var etag = app.get('etag fn');
    if (etag && !this.get('ETag')) {
      etag = etag(chunk, encoding);
      etag && this.set('ETag', etag);
    }
  }
 
  // freshness
  if (req.fresh) this.statusCode = 304;
 
  // strip irrelevant headers
  if (204 == this.statusCode || 304 == this.statusCode) {
    this.removeHeader('Content-Type');
    this.removeHeader('Content-Length');
    this.removeHeader('Transfer-Encoding');
    chunk = '';
  }
 
  // skip body for HEAD
  if (isHead) {
    this.end();
  }
 
  // respond
  this.end(chunk, encoding);
 
  return this;
};
 
/**
 * Send JSON response.
 *
 * Examples:
 *
 *     res.json(null);
 *     res.json({ user: 'tj' });
 *
 * @param {string|number|boolean|object} obj
 * @api public
 */
 
res.json = function json(obj) {
  var val = obj;
 
  // support res.json(status, obj)
  if (arguments.length === 2) {
    deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
    this.statusCode = arguments[0];
    val = arguments[1];
  }
 
  // settings
  var app = this.app;
  var replacer = app.get('json replacer');
  var spaces = app.get('json spaces');
  var body = JSON.stringify(val, replacer, spaces);
 
  // content-type
  if (!this.get('Content-Type')) {
    this.set('Content-Type', 'application/json');
  }
 
  return this.send(body);
};
 
/**
 * Send JSON response with JSONP callback support.
 *
 * Examples:
 *
 *     res.jsonp(null);
 *     res.jsonp({ user: 'tj' });
 *
 * @param {string|number|boolean|object} obj
 * @api public
 */
 
res.jsonp = function jsonp(obj) {
  var val = obj;
 
  // support res.jsonp(status, obj)
  if (arguments.length === 2) {
    deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');
    this.statusCode = arguments[0];
    val = arguments[1];
  }
 
  // settings
  var app = this.app;
  var replacer = app.get('json replacer');
  var spaces = app.get('json spaces');
  var body = JSON.stringify(val, replacer, spaces);
  var callback = this.req.query[app.get('jsonp callback name')];
 
  // content-type
  if (!this.get('Content-Type')) {
    this.set('X-Content-Type-Options', 'nosniff');
    this.set('Content-Type', 'application/json');
  }
 
  // fixup callback
  if (Array.isArray(callback)) {
    callback = callback[0];
  }
 
  // jsonp
  if (typeof callback === 'string' && callback.length !== 0) {
    this.charset = 'utf-8';
    this.set('X-Content-Type-Options', 'nosniff');
    this.set('Content-Type', 'text/javascript');
 
    // restrict callback charset
    callback = callback.replace(/[^\[\]\w$.]/g, '');
 
    // replace chars not allowed in JavaScript that are in JSON
    body = body
      .replace(/\u2028/g, '\\u2028')
      .replace(/\u2029/g, '\\u2029');
 
    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
    // the typeof check is just to reduce client error noise
    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
  }
 
  return this.send(body);
};
 
/**
 * Send given HTTP status code.
 *
 * Sets the response status to `statusCode` and the body of the
 * response to the standard description from node's http.STATUS_CODES
 * or the statusCode number if no description.
 *
 * Examples:
 *
 *     res.sendStatus(200);
 *
 * @param {number} statusCode
 * @api public
 */
 
res.sendStatus = function sendStatus(statusCode) {
  var body = http.STATUS_CODES[statusCode] || String(statusCode);
 
  this.statusCode = statusCode;
  this.type('txt');
 
  return this.send(body);
};
 
/**
 * Transfer the file at the given `path`.
 *
 * Automatically sets the _Content-Type_ response header field.
 * The callback `fn(err)` is invoked when the transfer is complete
 * or when an error occurs. Be sure to check `res.sentHeader`
 * if you wish to attempt responding, as the header and some data
 * may have already been transferred.
 *
 * Options:
 *
 *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)
 *   - `root`     root directory for relative filenames
 *   - `headers`  object of headers to serve with file
 *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
 *
 * Other options are passed along to `send`.
 *
 * Examples:
 *
 *  The following example illustrates how `res.sendFile()` may
 *  be used as an alternative for the `static()` middleware for
 *  dynamic situations. The code backing `res.sendFile()` is actually
 *  the same code, so HTTP cache support etc is identical.
 *
 *     app.get('/user/:uid/photos/:file', function(req, res){
 *       var uid = req.params.uid
 *         , file = req.params.file;
 *
 *       req.user.mayViewFilesFrom(uid, function(yes){
 *         if (yes) {
 *           res.sendFile('/uploads/' + uid + '/' + file);
 *         } else {
 *           res.send(403, 'Sorry! you cant see that.');
 *         }
 *       });
 *     });
 *
 * @api public
 */
 
res.sendFile = function sendFile(path, options, fn) {
  var req = this.req;
  var res = this;
  var next = req.next;
 
  if (!path) {
    throw new TypeError('path argument is required to res.sendFile');
  }
 
  // support function as second arg
  if (typeof options === 'function') {
    fn = options;
    options = {};
  }
 
  options = options || {};
 
  if (!options.root && !isAbsolute(path)) {
    throw new TypeError('path must be absolute or specify root to res.sendFile');
  }
 
  // create file stream
  var pathname = encodeURI(path);
  var file = send(req, pathname, options);
 
  // transfer
  sendfile(res, file, options, function (err) {
    if (fn) return fn(err);
    if (err && err.code === 'EISDIR') return next();
 
    // next() all but aborted errors
    if (err && err.code !== 'ECONNABORT') {
      next(err);
    }
  });
};
 
/**
 * Transfer the file at the given `path` as an attachment.
 *
 * Optionally providing an alternate attachment `filename`,
 * and optional callback `fn(err)`. The callback is invoked
 * when the data transfer is complete, or when an error has
 * ocurred. Be sure to check `res.headersSent` if you plan to respond.
 *
 * This method uses `res.sendFile()`.
 *
 * @api public
 */
 
res.download = function download(path, filename, fn) {
  // support function as second arg
  if (typeof filename === 'function') {
    fn = filename;
    filename = null;
  }
 
  filename = filename || path;
 
  // set Content-Disposition when file is sent
  var headers = {
    'Content-Disposition': contentDisposition(filename)
  };
 
  // Resolve the full path for sendFile
  var fullPath = resolve(path);
 
  return this.sendFile(fullPath, { headers: headers }, fn);
};
 
/**
 * Set _Content-Type_ response header with `type` through `mime.lookup()`
 * when it does not contain "/", or set the Content-Type to `type` otherwise.
 *
 * Examples:
 *
 *     res.type('.html');
 *     res.type('html');
 *     res.type('json');
 *     res.type('application/json');
 *     res.type('png');
 *
 * @param {String} type
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.contentType =
res.type = function(type){
  return this.set('Content-Type', ~type.indexOf('/')
    ? type
    : mime.lookup(type));
};
 
/**
 * Respond to the Acceptable formats using an `obj`
 * of mime-type callbacks.
 *
 * This method uses `req.accepted`, an array of
 * acceptable types ordered by their quality values.
 * When "Accept" is not present the _first_ callback
 * is invoked, otherwise the first match is used. When
 * no match is performed the server responds with
 * 406 "Not Acceptable".
 *
 * Content-Type is set for you, however if you choose
 * you may alter this within the callback using `res.type()`
 * or `res.set('Content-Type', ...)`.
 *
 *    res.format({
 *      'text/plain': function(){
 *        res.send('hey');
 *      },
 *
 *      'text/html': function(){
 *        res.send('<p>hey</p>');
 *      },
 *
 *      'appliation/json': function(){
 *        res.send({ message: 'hey' });
 *      }
 *    });
 *
 * In addition to canonicalized MIME types you may
 * also use extnames mapped to these types:
 *
 *    res.format({
 *      text: function(){
 *        res.send('hey');
 *      },
 *
 *      html: function(){
 *        res.send('<p>hey</p>');
 *      },
 *
 *      json: function(){
 *        res.send({ message: 'hey' });
 *      }
 *    });
 *
 * By default Express passes an `Error`
 * with a `.status` of 406 to `next(err)`
 * if a match is not made. If you provide
 * a `.default` callback it will be invoked
 * instead.
 *
 * @param {Object} obj
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.format = function(obj){
  var req = this.req;
  var next = req.next;
 
  var fn = obj.default;
  if (fn) delete obj.default;
  var keys = Object.keys(obj);
 
  var key = req.accepts(keys);
 
  this.vary("Accept");
 
  if (key) {
    this.set('Content-Type', normalizeType(key).value);
    obj[key](req, this, next);
  } else if (fn) {
    fn();
  } else {
    var err = new Error('Not Acceptable');
    err.status = 406;
    err.types = normalizeTypes(keys).map(function(o){ return o.value });
    next(err);
  }
 
  return this;
};
 
/**
 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
 *
 * @param {String} filename
 * @return {ServerResponse}
 * @api public
 */
 
res.attachment = function attachment(filename) {
  if (filename) {
    this.type(extname(filename));
  }
 
  this.set('Content-Disposition', contentDisposition(filename));
 
  return this;
};
 
/**
 * Set header `field` to `val`, or pass
 * an object of header fields.
 *
 * Examples:
 *
 *    res.set('Foo', ['bar', 'baz']);
 *    res.set('Accept', 'application/json');
 *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
 *
 * Aliased as `res.header()`.
 *
 * @param {String|Object|Array} field
 * @param {String} val
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.set =
res.header = function header(field, val) {
  if (arguments.length === 2) {
    if (Array.isArray(val)) val = val.map(String);
    else val = String(val);
    if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {
      var charset = mime.charsets.lookup(val.split(';')[0]);
      if (charset) val += '; charset=' + charset.toLowerCase();
    }
    this.setHeader(field, val);
  } else {
    for (var key in field) {
      this.set(key, field[key]);
    }
  }
  return this;
};
 
/**
 * Get value for header `field`.
 *
 * @param {String} field
 * @return {String}
 * @api public
 */
 
res.get = function(field){
  return this.getHeader(field);
};
 
/**
 * Clear cookie `name`.
 *
 * @param {String} name
 * @param {Object} options
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.clearCookie = function(name, options){
  var opts = { expires: new Date(1), path: '/' };
  return this.cookie(name, '', options
    ? merge(opts, options)
    : opts);
};
 
/**
 * Set cookie `name` to `val`, with the given `options`.
 *
 * Options:
 *
 *    - `maxAge`   max-age in milliseconds, converted to `expires`
 *    - `signed`   sign the cookie
 *    - `path`     defaults to "/"
 *
 * Examples:
 *
 *    // "Remember Me" for 15 minutes
 *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
 *
 *    // save as above
 *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
 *
 * @param {String} name
 * @param {String|Object} val
 * @param {Options} options
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.cookie = function(name, val, options){
  options = merge({}, options);
  var secret = this.req.secret;
  var signed = options.signed;
  if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');
  if ('number' == typeof val) val = val.toString();
  if ('object' == typeof val) val = 'j:' + JSON.stringify(val);
  if (signed) val = 's:' + sign(val, secret);
  if ('maxAge' in options) {
    options.expires = new Date(Date.now() + options.maxAge);
    options.maxAge /= 1000;
  }
  if (null == options.path) options.path = '/';
  var headerVal = cookie.serialize(name, String(val), options);
 
  // supports multiple 'res.cookie' calls by getting previous value
  var prev = this.get('Set-Cookie');
  if (prev) {
    if (Array.isArray(prev)) {
      headerVal = prev.concat(headerVal);
    } else {
      headerVal = [prev, headerVal];
    }
  }
  this.set('Set-Cookie', headerVal);
  return this;
};
 
 
/**
 * Set the location header to `url`.
 *
 * The given `url` can also be "back", which redirects
 * to the _Referrer_ or _Referer_ headers or "/".
 *
 * Examples:
 *
 *    res.location('/foo/bar').;
 *    res.location('http://example.com');
 *    res.location('../login');
 *
 * @param {String} url
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.location = function(url){
  var req = this.req;
 
  // "back" is an alias for the referrer
  if ('back' == url) url = req.get('Referrer') || '/';
 
  // Respond
  this.set('Location', url);
  return this;
};
 
/**
 * Redirect to the given `url` with optional response `status`
 * defaulting to 302.
 *
 * The resulting `url` is determined by `res.location()`, so
 * it will play nicely with mounted apps, relative paths,
 * `"back"` etc.
 *
 * Examples:
 *
 *    res.redirect('/foo/bar');
 *    res.redirect('http://example.com');
 *    res.redirect(301, 'http://example.com');
 *    res.redirect('../login'); // /blog/post/1 -> /blog/login
 *
 * @api public
 */
 
res.redirect = function redirect(url) {
  var address = url;
  var body;
  var status = 302;
 
  // allow status / url
  if (arguments.length === 2) {
    if (typeof arguments[0] === 'number') {
      status = arguments[0];
      address = arguments[1];
    } else {
      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
      status = arguments[1];
    }
  }
 
  // Set location header
  this.location(address);
  address = this.get('Location');
 
  // Support text/{plain,html} by default
  this.format({
    text: function(){
      body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);
    },
 
    html: function(){
      var u = escapeHtml(address);
      body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';
    },
 
    default: function(){
      body = '';
    }
  });
 
  // Respond
  this.statusCode = status;
  this.set('Content-Length', Buffer.byteLength(body));
 
  if (this.req.method === 'HEAD') {
    this.end();
  }
 
  this.end(body);
};
 
/**
 * Add `field` to Vary. If already present in the Vary set, then
 * this call is simply ignored.
 *
 * @param {Array|String} field
 * @return {ServerResponse} for chaining
 * @api public
 */
 
res.vary = function(field){
  // checks for back-compat
  if (!field || (Array.isArray(field) && !field.length)) {
    deprecate('res.vary(): Provide a field name');
    return this;
  }
 
  vary(this, field);
 
  return this;
};
 
/**
 * Render `view` with the given `options` and optional callback `fn`.
 * When a callback function is given a response will _not_ be made
 * automatically, otherwise a response of _200_ and _text/html_ is given.
 *
 * Options:
 *
 *  - `cache`     boolean hinting to the engine it should cache
 *  - `filename`  filename of the view being rendered
 *
 * @api public
 */
 
res.render = function(view, options, fn){
  options = options || {};
  var self = this;
  var req = this.req;
  var app = req.app;
 
  // support callback function as second arg
  if ('function' == typeof options) {
    fn = options, options = {};
  }
 
  // merge res.locals
  options._locals = self.locals;
 
  // default callback to respond
  fn = fn || function(err, str){
    if (err) return req.next(err);
    self.send(str);
  };
 
  // render
  app.render(view, options, fn);
};
 
// pipe the send file stream
function sendfile(res, file, options, callback) {
  var done = false;
 
  // directory
  function ondirectory() {
    if (done) return;
    done = true;
 
    var err = new Error('EISDIR, read');
    err.code = 'EISDIR';
    callback(err);
  }
 
  // errors
  function onerror(err) {
    if (done) return;
    done = true;
    callback(err);
  }
 
  // ended
  function onend() {
    if (done) return;
    done = true;
    callback();
  }
 
  // finished
  function onfinish(err) {
    if (err) return onerror(err);
    if (done) return;
 
    setImmediate(function () {
      if (done) return;
      done = true;
 
      // response finished before end of file
      var err = new Error('Request aborted');
      err.code = 'ECONNABORT';
      callback(err);
    });
  }
 
  file.on('end', onend);
  file.on('error', onerror);
  file.on('directory', ondirectory);
  onFinished(res, onfinish);
 
  if (options.headers) {
    // set headers on successful transfer
    file.on('headers', function headers(res) {
      var obj = options.headers;
      var keys = Object.keys(obj);
 
      for (var i = 0; i < keys.length; i++) {
        var k = keys[i];
        res.setHeader(k, obj[k]);
      }
    });
  }
 
  // pipe
  file.pipe(res);
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/utils.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/utils.js

Statements: 19.1% (17 / 89)      Branches: 0% (0 / 48)      Functions: 0% (0 / 13)      Lines: 20.73% (17 / 82)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258        1 1 1 1 1 1                     1                                 1                               1                           1                                         1                           1                                       1                                               1                                                                   1                                                                   1                                                           1                          
/**
 * Module dependencies.
 */
 
var mime = require('send').mime;
var etag = require('etag');
var proxyaddr = require('proxy-addr');
var qs = require('qs');
var querystring = require('querystring');
var typer = require('media-typer');
 
/**
 * Return strong ETag for `body`.
 *
 * @param {String|Buffer} body
 * @param {String} [encoding]
 * @return {String}
 * @api private
 */
 
exports.etag = function (body, encoding) {
  var buf = !Buffer.isBuffer(body)
    ? new Buffer(body, encoding)
    : body;
 
  return etag(buf, {weak: false});
};
 
/**
 * Return weak ETag for `body`.
 *
 * @param {String|Buffer} body
 * @param {String} [encoding]
 * @return {String}
 * @api private
 */
 
exports.wetag = function wetag(body, encoding){
  var buf = !Buffer.isBuffer(body)
    ? new Buffer(body, encoding)
    : body;
 
  return etag(buf, {weak: true});
};
 
/**
 * Check if `path` looks absolute.
 *
 * @param {String} path
 * @return {Boolean}
 * @api private
 */
 
exports.isAbsolute = function(path){
  if ('/' == path[0]) return true;
  if (':' == path[1] && '\\' == path[2]) return true;
  if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path
};
 
/**
 * Flatten the given `arr`.
 *
 * @param {Array} arr
 * @return {Array}
 * @api private
 */
 
exports.flatten = function(arr, ret){
  ret = ret || [];
  var len = arr.length;
  for (var i = 0; i < len; ++i) {
    if (Array.isArray(arr[i])) {
      exports.flatten(arr[i], ret);
    } else {
      ret.push(arr[i]);
    }
  }
  return ret;
};
 
/**
 * Normalize the given `type`, for example "html" becomes "text/html".
 *
 * @param {String} type
 * @return {Object}
 * @api private
 */
 
exports.normalizeType = function(type){
  return ~type.indexOf('/')
    ? acceptParams(type)
    : { value: mime.lookup(type), params: {} };
};
 
/**
 * Normalize `types`, for example "html" becomes "text/html".
 *
 * @param {Array} types
 * @return {Array}
 * @api private
 */
 
exports.normalizeTypes = function(types){
  var ret = [];
 
  for (var i = 0; i < types.length; ++i) {
    ret.push(exports.normalizeType(types[i]));
  }
 
  return ret;
};
 
/**
 * Parse accept params `str` returning an
 * object with `.value`, `.quality` and `.params`.
 * also includes `.originalIndex` for stable sorting
 *
 * @param {String} str
 * @return {Object}
 * @api private
 */
 
function acceptParams(str, index) {
  var parts = str.split(/ *; */);
  var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };
 
  for (var i = 1; i < parts.length; ++i) {
    var pms = parts[i].split(/ *= */);
    if ('q' == pms[0]) {
      ret.quality = parseFloat(pms[1]);
    } else {
      ret.params[pms[0]] = pms[1];
    }
  }
 
  return ret;
}
 
/**
 * Compile "etag" value to function.
 *
 * @param  {Boolean|String|Function} val
 * @return {Function}
 * @api private
 */
 
exports.compileETag = function(val) {
  var fn;
 
  if (typeof val === 'function') {
    return val;
  }
 
  switch (val) {
    case true:
      fn = exports.wetag;
      break;
    case false:
      break;
    case 'strong':
      fn = exports.etag;
      break;
    case 'weak':
      fn = exports.wetag;
      break;
    default:
      throw new TypeError('unknown value for etag function: ' + val);
  }
 
  return fn;
}
 
/**
 * Compile "query parser" value to function.
 *
 * @param  {String|Function} val
 * @return {Function}
 * @api private
 */
 
exports.compileQueryParser = function compileQueryParser(val) {
  var fn;
 
  if (typeof val === 'function') {
    return val;
  }
 
  switch (val) {
    case true:
      fn = querystring.parse;
      break;
    case false:
      break;
    case 'extended':
      fn = qs.parse;
      break;
    case 'simple':
      fn = querystring.parse;
      break;
    default:
      throw new TypeError('unknown value for query parser function: ' + val);
  }
 
  return fn;
}
 
/**
 * Compile "proxy trust" value to function.
 *
 * @param  {Boolean|String|Number|Array|Function} val
 * @return {Function}
 * @api private
 */
 
exports.compileTrust = function(val) {
  if (typeof val === 'function') return val;
 
  if (val === true) {
    // Support plain true/false
    return function(){ return true };
  }
 
  if (typeof val === 'number') {
    // Support trusting hop count
    return function(a, i){ return i < val };
  }
 
  if (typeof val === 'string') {
    // Support comma-separated values
    val = val.split(/ *, */);
  }
 
  return proxyaddr.compile(val || []);
}
 
/**
 * Set the charset in a given Content-Type string.
 *
 * @param {String} type
 * @param {String} charset
 * @return {String}
 * @api private
 */
 
exports.setCharset = function(type, charset){
  if (!type || !charset) return type;
 
  // parse type
  var parsed = typer.parse(type);
 
  // set charset
  parsed.parameters.charset = charset;
 
  // format type
  return typer.format(parsed);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/view.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/view.js

Statements: 27.78% (15 / 54)      Branches: 0% (0 / 22)      Functions: 0% (0 / 5)      Lines: 28.85% (15 / 52)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144        1 1 1 1             1 1 1 1 1           1                               1                                         1                                                         1                         1                                                           1                    
/**
 * Module dependencies.
 */
 
var debug = require('debug')('express:view');
var path = require('path');
var fs = require('fs');
var utils = require('./utils');
 
/**
 * Module variables.
 * @private
 */
 
var dirname = path.dirname;
var basename = path.basename;
var extname = path.extname;
var join = path.join;
var resolve = path.resolve;
 
/**
 * Expose `View`.
 */
 
module.exports = View;
 
/**
 * Initialize a new `View` with the given `name`.
 *
 * Options:
 *
 *   - `defaultEngine` the default template engine name
 *   - `engines` template engine require() cache
 *   - `root` root path for view lookup
 *
 * @param {String} name
 * @param {Object} options
 * @api private
 */
 
function View(name, options) {
  options = options || {};
  this.name = name;
  this.root = options.root;
  var engines = options.engines;
  this.defaultEngine = options.defaultEngine;
  var ext = this.ext = extname(name);
  if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
  if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
  this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
  this.path = this.lookup(name);
}
 
/**
 * Lookup view by the given `name`
 *
 * @param {String} name
 * @return {String}
 * @api private
 */
 
View.prototype.lookup = function lookup(name) {
  var path;
  var roots = [].concat(this.root);
 
  debug('lookup "%s"', name);
 
  for (var i = 0; i < roots.length && !path; i++) {
    var root = roots[i];
 
    // resolve the path
    var loc = resolve(root, name);
    var dir = dirname(loc);
    var file = basename(loc);
 
    // resolve the file
    path = this.resolve(dir, file);
  }
 
  return path;
};
 
/**
 * Render with the given `options` and callback `fn(err, str)`.
 *
 * @param {Object} options
 * @param {Function} fn
 * @api private
 */
 
View.prototype.render = function render(options, fn) {
  debug('render "%s"', this.path);
  this.engine(this.path, options, fn);
};
 
/**
 * Resolve the file within the given directory.
 *
 * @param {string} dir
 * @param {string} file
 * @private
 */
 
View.prototype.resolve = function resolve(dir, file) {
  var ext = this.ext;
  var path;
  var stat;
 
  // <path>.<ext>
  path = join(dir, file);
  stat = tryStat(path);
 
  if (stat && stat.isFile()) {
    return path;
  }
 
  // <path>/index.<ext>
  path = join(dir, basename(file, ext), 'index' + ext);
  stat = tryStat(path);
 
  if (stat && stat.isFile()) {
    return path;
  }
};
 
/**
 * Return a stat, maybe.
 *
 * @param {string} path
 * @return {fs.Stats}
 * @private
 */
 
function tryStat(path) {
  debug('stat "%s"', path);
 
  try {
    return fs.statSync(path);
  } catch (e) {
    return undefined;
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/

Statements: 13.37% (50 / 374)      Branches: 0% (0 / 188)      Functions: 5% (2 / 40)      Lines: 13.55% (50 / 369)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/lib/router/
File Statements Branches Functions Lines
index.js 11.67% (28 / 240) 0% (0 / 132) 4.17% (1 / 24) 11.91% (28 / 235)
layer.js 13.43% (9 / 67) 0% (0 / 28) 0% (0 / 5) 13.43% (9 / 67)
route.js 19.4% (13 / 67) 0% (0 / 28) 9.09% (1 / 11) 19.4% (13 / 67)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/index.js

Statements: 11.67% (28 / 240)      Branches: 0% (0 / 132)      Functions: 4.17% (1 / 24)      Lines: 11.91% (28 / 235)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577          1 1 1 1 1 1 1           1 1 1                   1     1                                                                                                     1                                                                           1                                                                                         1                                                                                                                                                     1                                                                             1                                             1                                         1                                                                                       1                                                                               1                                                                                                                         1                               1 34               1                         1                                                                       1                                       1                          
 
/**
 * Module dependencies.
 */
 
var Route = require('./route');
var Layer = require('./layer');
var methods = require('methods');
var mixin = require('utils-merge');
var debug = require('debug')('express:router');
var parseUrl = require('parseurl');
var utils = require('../utils');
 
/**
 * Module variables.
 */
 
var objectRegExp = /^\[object (\S+)\]$/;
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
 
/**
 * Initialize a new `Router` with the given `options`.
 *
 * @param {Object} options
 * @return {Router} which is an callable function
 * @api public
 */
 
var proto = module.exports = function(options) {
  options = options || {};
 
  function router(req, res, next) {
    router.handle(req, res, next);
  }
 
  // mixin Router class functions
  router.__proto__ = proto;
 
  router.params = {};
  router._params = [];
  router.caseSensitive = options.caseSensitive;
  router.mergeParams = options.mergeParams;
  router.strict = options.strict;
  router.stack = [];
 
  return router;
};
 
/**
 * Map the given param placeholder `name`(s) to the given callback.
 *
 * Parameter mapping is used to provide pre-conditions to routes
 * which use normalized placeholders. For example a _:user_id_ parameter
 * could automatically load a user's information from the database without
 * any additional code,
 *
 * The callback uses the same signature as middleware, the only difference
 * being that the value of the placeholder is passed, in this case the _id_
 * of the user. Once the `next()` function is invoked, just like middleware
 * it will continue on to execute the route, or subsequent parameter functions.
 *
 * Just like in middleware, you must either respond to the request or call next
 * to avoid stalling the request.
 *
 *  app.param('user_id', function(req, res, next, id){
 *    User.find(id, function(err, user){
 *      if (err) {
 *        return next(err);
 *      } else if (!user) {
 *        return next(new Error('failed to load user'));
 *      }
 *      req.user = user;
 *      next();
 *    });
 *  });
 *
 * @param {String} name
 * @param {Function} fn
 * @return {app} for chaining
 * @api public
 */
 
proto.param = function(name, fn){
  // param logic
  if ('function' == typeof name) {
    this._params.push(name);
    return;
  }
 
  // apply param functions
  var params = this._params;
  var len = params.length;
  var ret;
 
  if (name[0] === ':') {
    name = name.substr(1);
  }
 
  for (var i = 0; i < len; ++i) {
    if (ret = params[i](name, fn)) {
      fn = ret;
    }
  }
 
  // ensure we end up with a
  // middleware function
  if ('function' != typeof fn) {
    throw new Error('invalid param() call for ' + name + ', got ' + fn);
  }
 
  (this.params[name] = this.params[name] || []).push(fn);
  return this;
};
 
/**
 * Dispatch a req, res into the router.
 *
 * @api private
 */
 
proto.handle = function(req, res, done) {
  var self = this;
 
  debug('dispatching %s %s', req.method, req.url);
 
  var search = 1 + req.url.indexOf('?');
  var pathlength = search ? search - 1 : req.url.length;
  var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://');
  var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '';
  var idx = 0;
  var removed = '';
  var slashAdded = false;
  var paramcalled = {};
 
  // store options for OPTIONS request
  // only used if OPTIONS request
  var options = [];
 
  // middleware and routes
  var stack = self.stack;
 
  // manage inter-router variables
  var parentParams = req.params;
  var parentUrl = req.baseUrl || '';
  done = restore(done, req, 'baseUrl', 'next', 'params');
 
  // setup next layer
  req.next = next;
 
  // for options requests, respond with a default if nothing else responds
  if (req.method === 'OPTIONS') {
    done = wrap(done, function(old, err) {
      if (err || options.length === 0) return old(err);
 
      var body = options.join(',');
      return res.set('Allow', body).send(body);
    });
  }
 
  // setup basic req values
  req.baseUrl = parentUrl;
  req.originalUrl = req.originalUrl || req.url;
 
  next();
 
  function next(err) {
    var layerError = err === 'route'
      ? null
      : err;
 
    var layer = stack[idx++];
 
    if (slashAdded) {
      req.url = req.url.substr(1);
      slashAdded = false;
    }
 
    if (removed.length !== 0) {
      req.baseUrl = parentUrl;
      req.url = protohost + removed + req.url.substr(protohost.length);
      removed = '';
    }
 
    if (!layer) {
      return done(layerError);
    }
 
    self.match_layer(layer, req, res, function (err, path) {
      if (err || path === undefined) {
        return next(layerError || err);
      }
 
      // route object and not middleware
      var route = layer.route;
 
      // if final route, then we support options
      if (route) {
        // we don't run any routes with error first
        if (layerError) {
          return next(layerError);
        }
 
        var method = req.method;
        var has_method = route._handles_method(method);
 
        // build up automatic options response
        if (!has_method && method === 'OPTIONS') {
          options.push.apply(options, route._options());
        }
 
        // don't even bother
        if (!has_method && method !== 'HEAD') {
          return next();
        }
 
        // we can now dispatch to the route
        req.route = route;
      }
 
      // Capture one-time layer values
      req.params = self.mergeParams
        ? mergeParams(layer.params, parentParams)
        : layer.params;
      var layerPath = layer.path;
 
      // this should be done for the layer
      self.process_params(layer, paramcalled, req, res, function (err) {
        if (err) {
          return next(layerError || err);
        }
 
        if (route) {
          return layer.handle_request(req, res, next);
        }
 
        trim_prefix(layer, layerError, layerPath, path);
      });
    });
  }
 
  function trim_prefix(layer, layerError, layerPath, path) {
    var c = path[layerPath.length];
    if (c && '/' !== c && '.' !== c) return next(layerError);
 
     // Trim off the part of the url that matches the route
     // middleware (.use stuff) needs to have the path stripped
    if (layerPath.length !== 0) {
      debug('trim prefix (%s) from url %s', layerPath, req.url);
      removed = layerPath;
      req.url = protohost + req.url.substr(protohost.length + removed.length);
 
      // Ensure leading slash
      if (!fqdn && req.url[0] !== '/') {
        req.url = '/' + req.url;
        slashAdded = true;
      }
 
      // Setup base URL (no trailing slash)
      req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'
        ? removed.substring(0, removed.length - 1)
        : removed);
    }
 
    debug('%s %s : %s', layer.name, layerPath, req.originalUrl);
 
    if (layerError) {
      layer.handle_error(layerError, req, res, next);
    } else {
      layer.handle_request(req, res, next);
    }
  }
};
 
/**
 * Match request to a layer.
 *
 * @api private
 */
 
proto.match_layer = function match_layer(layer, req, res, done) {
  var error = null;
  var path;
 
  try {
    path = parseUrl(req).pathname;
 
    if (!layer.match(path)) {
      path = undefined;
    }
  } catch (err) {
    error = err;
  }
 
  done(error, path);
};
 
/**
 * Process any parameters for the layer.
 *
 * @api private
 */
 
proto.process_params = function(layer, called, req, res, done) {
  var params = this.params;
 
  // captured parameters from the layer, keys and values
  var keys = layer.keys;
 
  // fast track
  if (!keys || keys.length === 0) {
    return done();
  }
 
  var i = 0;
  var name;
  var paramIndex = 0;
  var key;
  var paramVal;
  var paramCallbacks;
  var paramCalled;
 
  // process params in order
  // param callbacks can be async
  function param(err) {
    if (err) {
      return done(err);
    }
 
    if (i >= keys.length ) {
      return done();
    }
 
    paramIndex = 0;
    key = keys[i++];
 
    if (!key) {
      return done();
    }
 
    name = key.name;
    paramVal = req.params[name];
    paramCallbacks = params[name];
    paramCalled = called[name];
 
    if (paramVal === undefined || !paramCallbacks) {
      return param();
    }
 
    // param previously called with same value or error occurred
    if (paramCalled && (paramCalled.error || paramCalled.match === paramVal)) {
      // restore value
      req.params[name] = paramCalled.value;
 
      // next param
      return param(paramCalled.error);
    }
 
    called[name] = paramCalled = {
      error: null,
      match: paramVal,
      value: paramVal
    };
 
    paramCallback();
  }
 
  // single param callbacks
  function paramCallback(err) {
    var fn = paramCallbacks[paramIndex++];
 
    // store updated value
    paramCalled.value = req.params[key.name];
 
    if (err) {
      // store error
      paramCalled.error = err;
      param(err);
      return;
    }
 
    if (!fn) return param();
 
    try {
      fn(req, res, paramCallback, paramVal, key.name);
    } catch (e) {
      paramCallback(e);
    }
  }
 
  param();
};
 
/**
 * Use the given middleware function, with optional path, defaulting to "/".
 *
 * Use (like `.all`) will run for any http METHOD, but it will not add
 * handlers for those methods so OPTIONS requests will not consider `.use`
 * functions even if they could respond.
 *
 * The other difference is that _route_ path is stripped and not visible
 * to the handler function. The main effect of this feature is that mounted
 * handlers can operate without any code changes regardless of the "prefix"
 * pathname.
 *
 * @api public
 */
 
proto.use = function use(fn) {
  var offset = 0;
  var path = '/';
 
  // default path to '/'
  // disambiguate router.use([fn])
  if (typeof fn !== 'function') {
    var arg = fn;
 
    while (Array.isArray(arg) && arg.length !== 0) {
      arg = arg[0];
    }
 
    // first arg is the path
    if (typeof arg !== 'function') {
      offset = 1;
      path = fn;
    }
  }
 
  var callbacks = utils.flatten(slice.call(arguments, offset));
 
  if (callbacks.length === 0) {
    throw new TypeError('Router.use() requires middleware functions');
  }
 
  callbacks.forEach(function (fn) {
    if (typeof fn !== 'function') {
      throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
    }
 
    // add the middleware
    debug('use %s %s', path, fn.name || '<anonymous>');
 
    var layer = new Layer(path, {
      sensitive: this.caseSensitive,
      strict: false,
      end: false
    }, fn);
 
    layer.route = undefined;
 
    this.stack.push(layer);
  }, this);
 
  return this;
};
 
/**
 * Create a new Route for the given path.
 *
 * Each route contains a separate middleware stack and VERB handlers.
 *
 * See the Route api documentation for details on adding handlers
 * and middleware to routes.
 *
 * @param {String} path
 * @return {Route}
 * @api public
 */
 
proto.route = function(path){
  var route = new Route(path);
 
  var layer = new Layer(path, {
    sensitive: this.caseSensitive,
    strict: this.strict,
    end: true
  }, route.dispatch.bind(route));
 
  layer.route = route;
 
  this.stack.push(layer);
  return route;
};
 
// create Router#VERB functions
methods.concat('all').forEach(function(method){
  proto[method] = function(path){
    var route = this.route(path)
    route[method].apply(route, slice.call(arguments, 1));
    return this;
  };
});
 
// get type for error message
function gettype(obj) {
  var type = typeof obj;
 
  if (type !== 'object') {
    return type;
  }
 
  // inspect [[Class]] for objects
  return toString.call(obj)
    .replace(objectRegExp, '$1');
}
 
// merge params with parent params
function mergeParams(params, parent) {
  if (typeof parent !== 'object' || !parent) {
    return params;
  }
 
  // make copy of parent for base
  var obj = mixin({}, parent);
 
  // simple non-numeric merging
  if (!(0 in params) || !(0 in parent)) {
    return mixin(obj, params);
  }
 
  var i = 0;
  var o = 0;
 
  // determine numeric gaps
  while (i === o || o in parent) {
    if (i in params) i++;
    if (o in parent) o++;
  }
 
  // offset numeric indices in params before merge
  for (i--; i >= 0; i--) {
    params[i + o] = params[i];
 
    // create holes for the merge when necessary
    if (i < o) {
      delete params[i];
    }
  }
 
  return mixin(parent, params);
}
 
// restore obj props after function
function restore(fn, obj) {
  var props = new Array(arguments.length - 2);
  var vals = new Array(arguments.length - 2);
 
  for (var i = 0; i < props.length; i++) {
    props[i] = arguments[i + 2];
    vals[i] = obj[props[i]];
  }
 
  return function(err){
    // restore vals
    for (var i = 0; i < props.length; i++) {
      obj[props[i]] = vals[i];
    }
 
    return fn.apply(this, arguments);
  };
}
 
// wrap a function
function wrap(old, fn) {
  return function proxy() {
    var args = new Array(arguments.length + 1);
 
    args[0] = old;
    for (var i = 0, len = arguments.length; i < len; i++) {
      args[i + 1] = arguments[i];
    }
 
    fn.apply(this, args);
  };
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/layer.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/layer.js

Statements: 13.43% (9 / 67)      Branches: 0% (0 / 28)      Functions: 0% (0 / 5)      Lines: 13.43% (9 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168        1 1           1           1   1                                                         1                                               1                                               1                                                                                                                 1                            
/**
 * Module dependencies.
 */
 
var pathRegexp = require('path-to-regexp');
var debug = require('debug')('express:router:layer');
 
/**
 * Module variables.
 */
 
var hasOwnProperty = Object.prototype.hasOwnProperty;
 
/**
 * Expose `Layer`.
 */
 
module.exports = Layer;
 
function Layer(path, options, fn) {
  if (!(this instanceof Layer)) {
    return new Layer(path, options, fn);
  }
 
  debug('new %s', path);
  options = options || {};
 
  this.handle = fn;
  this.name = fn.name || '<anonymous>';
  this.params = undefined;
  this.path = undefined;
  this.regexp = pathRegexp(path, this.keys = [], options);
 
  if (path === '/' && options.end === false) {
    this.regexp.fast_slash = true;
  }
}
 
/**
 * Handle the error for the layer.
 *
 * @param {Error} error
 * @param {Request} req
 * @param {Response} res
 * @param {function} next
 * @api private
 */
 
Layer.prototype.handle_error = function handle_error(error, req, res, next) {
  var fn = this.handle;
 
  if (fn.length !== 4) {
    // not a standard error handler
    return next(error);
  }
 
  try {
    fn(error, req, res, next);
  } catch (err) {
    next(err);
  }
};
 
/**
 * Handle the request for the layer.
 *
 * @param {Request} req
 * @param {Response} res
 * @param {function} next
 * @api private
 */
 
Layer.prototype.handle_request = function handle(req, res, next) {
  var fn = this.handle;
 
  if (fn.length > 3) {
    // not a standard request handler
    return next();
  }
 
  try {
    fn(req, res, next);
  } catch (err) {
    next(err);
  }
};
 
/**
 * Check if this route matches `path`, if so
 * populate `.params`.
 *
 * @param {String} path
 * @return {Boolean}
 * @api private
 */
 
Layer.prototype.match = function match(path) {
  if (path == null) {
    // no path, nothing matches
    this.params = undefined;
    this.path = undefined;
    return false;
  }
 
  if (this.regexp.fast_slash) {
    // fast path non-ending match for / (everything matches)
    this.params = {};
    this.path = '';
    return true;
  }
 
  var m = this.regexp.exec(path);
 
  if (!m) {
    this.params = undefined;
    this.path = undefined;
    return false;
  }
 
  // store values
  this.params = {};
  this.path = m[0];
 
  var keys = this.keys;
  var params = this.params;
  var prop;
  var n = 0;
  var key;
  var val;
 
  for (var i = 1, len = m.length; i < len; ++i) {
    key = keys[i - 1];
    prop = key
      ? key.name
      : n++;
    val = decode_param(m[i]);
 
    if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
      params[prop] = val;
    }
  }
 
  return true;
};
 
/**
 * Decode param value.
 *
 * @param {string} val
 * @return {string}
 * @api private
 */
 
function decode_param(val){
  if (typeof val !== 'string') {
    return val;
  }
 
  try {
    return decodeURIComponent(val);
  } catch (e) {
    var err = new TypeError("Failed to decode param '" + val + "'");
    err.status = 400;
    throw err;
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/route.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/lib/router/route.js

Statements: 19.4% (13 / 67)      Branches: 0% (0 / 28)      Functions: 9.09% (1 / 11)      Lines: 19.4% (13 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175        1 1 1 1           1                 1                         1                                     1                       1                               1                                                                                                   1                                     1 33                                            
/**
 * Module dependencies.
 */
 
var debug = require('debug')('express:router:route');
var Layer = require('./layer');
var methods = require('methods');
var utils = require('../utils');
 
/**
 * Expose `Route`.
 */
 
module.exports = Route;
 
/**
 * Initialize `Route` with the given `path`,
 *
 * @param {String} path
 * @api private
 */
 
function Route(path) {
  debug('new %s', path);
  this.path = path;
  this.stack = [];
 
  // route handlers for various http methods
  this.methods = {};
}
 
/**
 * @api private
 */
 
Route.prototype._handles_method = function _handles_method(method) {
  if (this.methods._all) {
    return true;
  }
 
  method = method.toLowerCase();
 
  if (method === 'head' && !this.methods['head']) {
    method = 'get';
  }
 
  return Boolean(this.methods[method]);
};
 
/**
 * @return {Array} supported HTTP methods
 * @api private
 */
 
Route.prototype._options = function(){
  return Object.keys(this.methods).map(function(method) {
    return method.toUpperCase();
  });
};
 
/**
 * dispatch req, res into this route
 *
 * @api private
 */
 
Route.prototype.dispatch = function(req, res, done){
  var idx = 0;
  var stack = this.stack;
  if (stack.length === 0) {
    return done();
  }
 
  var method = req.method.toLowerCase();
  if (method === 'head' && !this.methods['head']) {
    method = 'get';
  }
 
  req.route = this;
 
  next();
 
  function next(err) {
    if (err && err === 'route') {
      return done();
    }
 
    var layer = stack[idx++];
    if (!layer) {
      return done(err);
    }
 
    if (layer.method && layer.method !== method) {
      return next(err);
    }
 
    if (err) {
      layer.handle_error(err, req, res, next);
    } else {
      layer.handle_request(req, res, next);
    }
  }
};
 
/**
 * Add a handler for all HTTP verbs to this route.
 *
 * Behaves just like middleware and can respond or call `next`
 * to continue processing.
 *
 * You can use multiple `.all` call to add multiple handlers.
 *
 *   function check_something(req, res, next){
 *     next();
 *   };
 *
 *   function validate_user(req, res, next){
 *     next();
 *   };
 *
 *   route
 *   .all(validate_user)
 *   .all(check_something)
 *   .get(function(req, res, next){
 *     res.send('hello world');
 *   });
 *
 * @param {function} handler
 * @return {Route} for chaining
 * @api public
 */
 
Route.prototype.all = function(){
  var callbacks = utils.flatten([].slice.call(arguments));
  callbacks.forEach(function(fn) {
    if (typeof fn !== 'function') {
      var type = {}.toString.call(fn);
      var msg = 'Route.all() requires callback functions but got a ' + type;
      throw new Error(msg);
    }
 
    var layer = Layer('/', {}, fn);
    layer.method = undefined;
 
    this.methods._all = true;
    this.stack.push(layer);
  }, this);
 
  return this;
};
 
methods.forEach(function(method){
  Route.prototype[method] = function(){
    var callbacks = utils.flatten([].slice.call(arguments));
 
    callbacks.forEach(function(fn) {
      if (typeof fn !== 'function') {
        var type = {}.toString.call(fn);
        var msg = 'Route.' + method + '() requires callback functions but got a ' + type;
        throw new Error(msg);
      }
 
      debug('%s %s', method, this.path);
 
      var layer = Layer('/', {}, fn);
      layer.method = method;
 
      this.methods[method] = true;
      this.stack.push(layer);
    }, this);
    return this;
  };
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/

Statements: 20.37% (11 / 54)      Branches: 0% (0 / 34)      Functions: 0% (0 / 7)      Lines: 26.83% (11 / 41)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/
File Statements Branches Functions Lines
index.js 20.37% (11 / 54) 0% (0 / 34) 0% (0 / 7) 26.83% (11 / 41)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/index.js

Statements: 20.37% (11 / 54)      Branches: 0% (0 / 34)      Functions: 0% (0 / 7)      Lines: 26.83% (11 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 1621 1   1   1   1                                                                                                 1                                                   1                                         1                                           1                                     1                         1        
var Negotiator = require('negotiator')
var mime = require('mime-types')
 
var slice = [].slice
 
module.exports = Accepts
 
function Accepts(req) {
  if (!(this instanceof Accepts))
    return new Accepts(req)
 
  this.headers = req.headers
  this.negotiator = Negotiator(req)
}
 
/**
 * Check if the given `type(s)` is acceptable, returning
 * the best match when true, otherwise `undefined`, in which
 * case you should respond with 406 "Not Acceptable".
 *
 * The `type` value may be a single mime type string
 * such as "application/json", the extension name
 * such as "json" or an array `["json", "html", "text/plain"]`. When a list
 * or array is given the _best_ match, if any is returned.
 *
 * Examples:
 *
 *     // Accept: text/html
 *     this.types('html');
 *     // => "html"
 *
 *     // Accept: text/*, application/json
 *     this.types('html');
 *     // => "html"
 *     this.types('text/html');
 *     // => "text/html"
 *     this.types('json', 'text');
 *     // => "json"
 *     this.types('application/json');
 *     // => "application/json"
 *
 *     // Accept: text/*, application/json
 *     this.types('image/png');
 *     this.types('png');
 *     // => undefined
 *
 *     // Accept: text/*;q=.5, application/json
 *     this.types(['html', 'json']);
 *     this.types('html', 'json');
 *     // => "json"
 *
 * @param {String|Array} type(s)...
 * @return {String|Array|Boolean}
 * @api public
 */
 
Accepts.prototype.type =
Accepts.prototype.types = function (types) {
  if (!Array.isArray(types)) types = slice.call(arguments);
  var n = this.negotiator;
  if (!types.length) return n.mediaTypes();
  if (!this.headers.accept) return types[0];
  var mimes = types.map(extToMime);
  var accepts = n.mediaTypes(mimes.filter(validMime));
  var first = accepts[0];
  if (!first) return false;
  return types[mimes.indexOf(first)];
}
 
/**
 * Return accepted encodings or best fit based on `encodings`.
 *
 * Given `Accept-Encoding: gzip, deflate`
 * an array sorted by quality is returned:
 *
 *     ['gzip', 'deflate']
 *
 * @param {String|Array} encoding(s)...
 * @return {String|Array}
 * @api public
 */
 
Accepts.prototype.encoding =
Accepts.prototype.encodings = function (encodings) {
  if (!Array.isArray(encodings)) encodings = slice.call(arguments);
  var n = this.negotiator;
  if (!encodings.length) return n.encodings();
  return n.encodings(encodings)[0] || false;
}
 
/**
 * Return accepted charsets or best fit based on `charsets`.
 *
 * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
 * an array sorted by quality is returned:
 *
 *     ['utf-8', 'utf-7', 'iso-8859-1']
 *
 * @param {String|Array} charset(s)...
 * @return {String|Array}
 * @api public
 */
 
Accepts.prototype.charset =
Accepts.prototype.charsets = function (charsets) {
  if (!Array.isArray(charsets)) charsets = [].slice.call(arguments);
  var n = this.negotiator;
  if (!charsets.length) return n.charsets();
  if (!this.headers['accept-charset']) return charsets[0];
  return n.charsets(charsets)[0] || false;
}
 
/**
 * Return accepted languages or best fit based on `langs`.
 *
 * Given `Accept-Language: en;q=0.8, es, pt`
 * an array sorted by quality is returned:
 *
 *     ['es', 'pt', 'en']
 *
 * @param {String|Array} lang(s)...
 * @return {Array|String}
 * @api public
 */
 
Accepts.prototype.lang =
Accepts.prototype.langs =
Accepts.prototype.language =
Accepts.prototype.languages = function (langs) {
  if (!Array.isArray(langs)) langs = slice.call(arguments);
  var n = this.negotiator;
  if (!langs.length) return n.languages();
  if (!this.headers['accept-language']) return langs[0];
  return n.languages(langs)[0] || false;
}
 
/**
 * Convert extnames to mime.
 *
 * @param {String} type
 * @return {String}
 * @api private
 */
 
function extToMime(type) {
  if (~type.indexOf('/')) return type;
  return mime.lookup(type);
}
 
/**
 * Check if mime is valid.
 *
 * @param {String} type
 * @return {String}
 * @api private
 */
 
function validMime(type) {
  return typeof type === 'string';
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/
File Statements Branches Functions Lines
index.js 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/index.js

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  1     1   1   1 1799 1799 1799 789 789 1018       1               1                     1                     1         1                      
 
var db = require('mime-db')
 
// types[extension] = type
exports.types = Object.create(null)
// extensions[type] = [extensions]
exports.extensions = Object.create(null)
 
Object.keys(db).forEach(function (name) {
  var mime = db[name]
  var exts = mime.extensions
  if (!exts || !exts.length) return
  exports.extensions[name] = exts
  exts.forEach(function (ext) {
    exports.types[ext] = name
  })
})
 
exports.lookup = function (string) {
  if (!string || typeof string !== "string") return false
  // remove any leading paths, though we should just use path.basename
  string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
  if (!string) return false
  return exports.types[string] || false
}
 
exports.extension = function (type) {
  if (!type || typeof type !== "string") return false
  // to do: use media-typer
  type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
  if (!type) return false
  var exts = exports.extensions[type[1].toLowerCase()]
  if (!exts || !exts.length) return false
  return exts[0]
}
 
// type has to be an exact mime type
exports.charset = function (type) {
  var mime = db[type]
  if (mime && mime.charset) return mime.charset
 
  // default text/* to utf-8
  if (/^text\//.test(type)) return 'UTF-8'
 
  return false
}
 
// backwards compatibility
exports.charsets = {
  lookup: exports.charset
}
 
// to do: maybe use set-type module or something
exports.contentType = function (type) {
  if (!type || typeof type !== "string") return false
  if (!~type.indexOf('/')) type = exports.lookup(type)
  if (!type) return false
  if (!~type.indexOf('charset')) {
    var charset = exports.charset(type)
    if (charset) type += '; charset=' + charset.toLowerCase()
  }
  return type
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/mime-types/node_modules/mime-db/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13                    1    
/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = require('./db.json')
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/

Statements: 16.6% (40 / 241)      Branches: 0% (0 / 152)      Functions: 2.74% (2 / 73)      Lines: 17.24% (40 / 232)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/
File Statements Branches Functions Lines
charset.js 14.89% (7 / 47) 0% (0 / 29) 0% (0 / 16) 15.22% (7 / 46)
encoding.js 11.86% (7 / 59) 0% (0 / 37) 0% (0 / 17) 12.07% (7 / 58)
language.js 12.5% (7 / 56) 0% (0 / 37) 0% (0 / 16) 13.46% (7 / 52)
mediaType.js 11.67% (7 / 60) 0% (0 / 45) 0% (0 / 19) 11.86% (7 / 59)
negotiator.js 63.16% (12 / 19) 0% (0 / 4) 40% (2 / 5) 70.59% (12 / 17)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js

Statements: 14.89% (7 / 47)      Branches: 0% (0 / 29)      Functions: 0% (0 / 16)      Lines: 15.22% (7 / 46)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 891 1   1               1                                               1                       1                           1                                                      
module.exports = preferredCharsets;
preferredCharsets.preferredCharsets = preferredCharsets;
 
function parseAcceptCharset(accept) {
  return accept.split(',').map(function(e, i) {
    return parseCharset(e.trim(), i);
  }).filter(function(e) {
    return e;
  });
}
 
function parseCharset(s, i) {
  var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
  if (!match) return null;
 
  var charset = match[1];
  var q = 1;
  if (match[2]) {
    var params = match[2].split(';')
    for (var i = 0; i < params.length; i ++) {
      var p = params[i].trim().split('=');
      if (p[0] === 'q') {
        q = parseFloat(p[1]);
        break;
      }
    }
  }
 
  return {
    charset: charset,
    q: q,
    i: i
  };
}
 
function getCharsetPriority(charset, accepted) {
  return (accepted.map(function(a) {
    return specify(charset, a);
  }).filter(Boolean).sort(function (a, b) {
    if(a.s == b.s) {
      return a.q > b.q ? -1 : 1;
    } else {
      return a.s > b.s ? -1 : 1;
    }
  })[0] || {s: 0, q:0});
}
 
function specify(charset, spec) {
  var s = 0;
  if(spec.charset.toLowerCase() === charset.toLowerCase()){
    s |= 1;
  } else if (spec.charset !== '*' ) {
    return null
  }
 
  return {
    s: s,
    q: spec.q,
  }
}
 
function preferredCharsets(accept, provided) {
  // RFC 2616 sec 14.2: no header = *
  accept = parseAcceptCharset(accept === undefined ? '*' : accept || '');
  if (provided) {
    return provided.map(function(type) {
      return [type, getCharsetPriority(type, accept)];
    }).filter(function(pair) {
      return pair[1].q > 0;
    }).sort(function(a, b) {
      var pa = a[1];
      var pb = b[1];
      return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i);
    }).map(function(pair) {
      return pair[0];
    });
  } else {
    return accept.sort(function (a, b) {
      // revsort
      return (b.q - a.q) || (a.i - b.i);
    }).filter(function(type) {
      return type.q > 0;
    }).map(function(type) {
      return type.charset;
    });
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js

Statements: 11.86% (7 / 59)      Branches: 0% (0 / 37)      Functions: 0% (0 / 17)      Lines: 12.07% (7 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 1191 1   1                                                                           1                                                 1                       1                           1                                                    
module.exports = preferredEncodings;
preferredEncodings.preferredEncodings = preferredEncodings;
 
function parseAcceptEncoding(accept) {
  var acceptableEncodings;
 
  if (accept) {
    acceptableEncodings = accept.split(',').map(function(e, i) {
      return parseEncoding(e.trim(), i);
    });
  } else {
    acceptableEncodings = [];
  }
 
  if (!acceptableEncodings.some(function(e) {
    return e && specify('identity', e);
  })) {
    /*
     * If identity doesn't explicitly appear in the accept-encoding header,
     * it's added to the list of acceptable encoding with the lowest q
     *
     */
    var lowestQ = 1;
 
    for(var i = 0; i < acceptableEncodings.length; i++){
      var e = acceptableEncodings[i];
      if(e && e.q < lowestQ){
        lowestQ = e.q;
      }
    }
    acceptableEncodings.push({
      encoding: 'identity',
      q: lowestQ / 2,
    });
  }
 
  return acceptableEncodings.filter(function(e) {
    return e;
  });
}
 
function parseEncoding(s, i) {
  var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
 
  if (!match) return null;
 
  var encoding = match[1];
  var q = 1;
  if (match[2]) {
    var params = match[2].split(';');
    for (var i = 0; i < params.length; i ++) {
      var p = params[i].trim().split('=');
      if (p[0] === 'q') {
        q = parseFloat(p[1]);
        break;
      }
    }
  }
 
  return {
    encoding: encoding,
    q: q,
    i: i
  };
}
 
function getEncodingPriority(encoding, accepted) {
  return (accepted.map(function(a) {
    return specify(encoding, a);
  }).filter(Boolean).sort(function (a, b) {
    if(a.s == b.s) {
      return a.q > b.q ? -1 : 1;
    } else {
      return a.s > b.s ? -1 : 1;
    }
  })[0] || {s: 0, q: 0});
}
 
function specify(encoding, spec) {
  var s = 0;
  if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
    s |= 1;
  } else if (spec.encoding !== '*' ) {
    return null
  }
 
  return {
    s: s,
    q: spec.q,
  }
};
 
function preferredEncodings(accept, provided) {
  accept = parseAcceptEncoding(accept || '');
  if (provided) {
    return provided.map(function(type) {
      return [type, getEncodingPriority(type, accept)];
    }).filter(function(pair) {
      return pair[1].q > 0;
    }).sort(function(a, b) {
      var pa = a[1];
      var pb = b[1];
      return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i);
    }).map(function(pair) {
      return pair[0];
    });
  } else {
    return accept.sort(function (a, b) {
      // revsort
      return (b.q - a.q) || (a.i - b.i);
    }).filter(function(type){
      return type.q > 0;
    }).map(function(type) {
      return type.encoding;
    });
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js

Statements: 12.5% (7 / 56)      Branches: 0% (0 / 37)      Functions: 0% (0 / 16)      Lines: 13.46% (7 / 52)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 1021 1   1               1                                                       1                       1                                       1                                                            
module.exports = preferredLanguages;
preferredLanguages.preferredLanguages = preferredLanguages;
 
function parseAcceptLanguage(accept) {
  return accept.split(',').map(function(e, i) {
    return parseLanguage(e.trim(), i);
  }).filter(function(e) {
    return e;
  });
}
 
function parseLanguage(s, i) {
  var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/);
  if (!match) return null;
 
  var prefix = match[1],
      suffix = match[2],
      full = prefix;
 
  if (suffix) full += "-" + suffix;
 
  var q = 1;
  if (match[3]) {
    var params = match[3].split(';')
    for (var i = 0; i < params.length; i ++) {
      var p = params[i].split('=');
      if (p[0] === 'q') q = parseFloat(p[1]);
    }
  }
 
  return {
    prefix: prefix,
    suffix: suffix,
    q: q,
    i: i,
    full: full
  };
}
 
function getLanguagePriority(language, accepted) {
  return (accepted.map(function(a){
    return specify(language, a);
  }).filter(Boolean).sort(function (a, b) {
    if(a.s == b.s) {
      return a.q > b.q ? -1 : 1;
    } else {
      return a.s > b.s ? -1 : 1;
    }
  })[0] || {s: 0, q: 0});
}
 
function specify(language, spec) {
  var p = parseLanguage(language)
  if (!p) return null;
  var s = 0;
  if(spec.full.toLowerCase() === p.full.toLowerCase()){
    s |= 4;
  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
    s |= 2;
  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
    s |= 1;
  } else if (spec.full !== '*' ) {
    return null
  }
 
  return {
    s: s,
    q: spec.q,
  }
};
 
function preferredLanguages(accept, provided) {
  // RFC 2616 sec 14.4: no header = *
  accept = parseAcceptLanguage(accept === undefined ? '*' : accept || '');
  if (provided) {
 
    var ret = provided.map(function(type) {
      return [type, getLanguagePriority(type, accept)];
    }).filter(function(pair) {
      return pair[1].q > 0;
    }).sort(function(a, b) {
      var pa = a[1];
      var pb = b[1];
      return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i);
    }).map(function(pair) {
      return pair[0];
    });
    return ret;
 
  } else {
    return accept.sort(function (a, b) {
      // revsort
      return (b.q - a.q) || (a.i - b.i);
    }).filter(function(type) {
      return type.q > 0;
    }).map(function(type) {
      return type.full;
    });
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js

Statements: 11.67% (7 / 60)      Branches: 0% (0 / 45)      Functions: 0% (0 / 19)      Lines: 11.86% (7 / 59)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 1241 1   1               1                                                                   1                       1                                                                           1                                                        
module.exports = preferredMediaTypes;
preferredMediaTypes.preferredMediaTypes = preferredMediaTypes;
 
function parseAccept(accept) {
  return accept.split(',').map(function(e, i) {
    return parseMediaType(e.trim(), i);
  }).filter(function(e) {
    return e;
  });
};
 
function parseMediaType(s, i) {
  var match = s.match(/\s*(\S+?)\/([^;\s]+)\s*(?:;(.*))?/);
  if (!match) return null;
 
  var type = match[1],
      subtype = match[2],
      full = "" + type + "/" + subtype,
      params = {},
      q = 1;
 
  if (match[3]) {
    params = match[3].split(';').map(function(s) {
      return s.trim().split('=');
    }).reduce(function (set, p) {
      set[p[0]] = p[1];
      return set
    }, params);
 
    if (params.q != null) {
      q = parseFloat(params.q);
      delete params.q;
    }
  }
 
  return {
    type: type,
    subtype: subtype,
    params: params,
    q: q,
    i: i,
    full: full
  };
}
 
function getMediaTypePriority(type, accepted) {
  return (accepted.map(function(a) {
    return specify(type, a);
  }).filter(Boolean).sort(function (a, b) {
    if(a.s == b.s) {
      return a.q > b.q ? -1 : 1;
    } else {
      return a.s > b.s ? -1 : 1;
    }
  })[0] || {s: 0, q: 0});
}
 
function specify(type, spec) {
  var p = parseMediaType(type);
  var s = 0;
 
  if (!p) {
    return null;
  }
 
  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
    s |= 4
  } else if(spec.type != '*') {
    return null;
  }
 
  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
    s |= 2
  } else if(spec.subtype != '*') {
    return null;
  }
 
  var keys = Object.keys(spec.params);
  if (keys.length > 0) {
    if (keys.every(function (k) {
      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
    })) {
      s |= 1
    } else {
      return null
    }
  }
 
  return {
    q: spec.q,
    s: s,
  }
 
}
 
function preferredMediaTypes(accept, provided) {
  // RFC 2616 sec 14.2: no header = */*
  accept = parseAccept(accept === undefined ? '*/*' : accept || '');
  if (provided) {
    return provided.map(function(type) {
      return [type, getMediaTypePriority(type, accept)];
    }).filter(function(pair) {
      return pair[1].q > 0;
    }).sort(function(a, b) {
      var pa = a[1];
      var pb = b[1];
      return (pb.q - pa.q) || (pb.s - pa.s) || (pa.i - pb.i);
    }).map(function(pair) {
      return pair[0];
    });
 
  } else {
    return accept.sort(function (a, b) {
      // revsort
      return (b.q - a.q) || (a.i - b.i);
    }).filter(function(type) {
      return type.q > 0;
    }).map(function(type) {
      return type.full;
    });
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js

Statements: 63.16% (12 / 19)      Branches: 0% (0 / 4)      Functions: 40% (2 / 5)      Lines: 70.59% (12 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 391 1   1         1           1 8     1 4         4       4           4 4      
module.exports = Negotiator;
Negotiator.Negotiator = Negotiator;
 
function Negotiator(request) {
  if (!(this instanceof Negotiator)) return new Negotiator(request);
  this.request = request;
}
 
var set = { charset: 'accept-charset',
            encoding: 'accept-encoding',
            language: 'accept-language',
            mediaType: 'accept' };
 
 
function capitalize(string){
  return string.charAt(0).toUpperCase() + string.slice(1);
}
 
Object.keys(set).forEach(function (k) {
  var header = set[k],
      method = require('./'+k+'.js'),
      singular = k,
      plural = k + 's';
 
  Negotiator.prototype[plural] = function (available) {
    return method(this.request.headers[header], available);
  };
 
  Negotiator.prototype[singular] = function(available) {
    var set = this[plural](available);
    if (set) return set[0];
  };
 
  // Keep preferred* methods for legacy compatibility
  Negotiator.prototype['preferred'+capitalize(plural)] = Negotiator.prototype[plural];
  Negotiator.prototype['preferred'+capitalize(singular)] = Negotiator.prototype[singular];
})
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/content-disposition/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/content-disposition/

Statements: 20.66% (25 / 121)      Branches: 0% (0 / 75)      Functions: 0% (0 / 11)      Lines: 20.66% (25 / 121)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/content-disposition/
File Statements Branches Functions Lines
index.js 20.66% (25 / 121) 0% (0 / 75) 0% (0 / 11) 20.66% (25 / 121)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/content-disposition/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/content-disposition/index.js

Statements: 20.66% (25 / 121)      Branches: 0% (0 / 75)      Functions: 0% (0 / 11)      Lines: 20.66% (25 / 121)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445                    1 1           1           1           1 1           1                 1           1                                                   1 1 1                                             1                             1                         1                                           1                                                                                                                         1                                                                           1                                                                       1                         1                                                                                                                                                                 1                       1                                   1                           1                           1          
/*!
 * content-disposition
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = contentDisposition
module.exports.parse = parse
 
/**
 * Module dependencies.
 */
 
var basename = require('path').basename
 
/**
 * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%")
 */
 
var encodeUriAttrCharRegExp = /[\x00-\x20"'\(\)*,\/:;<=>?@\[\\\]\{\}\x7f]/g
 
/**
 * RegExp to match percent encoding escape.
 */
 
var hexEscapeRegExp = /%[0-9A-Fa-f]{2}/
var hexEscapeReplaceRegExp = /%([0-9A-Fa-f]{2})/g
 
/**
 * RegExp to match non-latin1 characters.
 */
 
var nonLatin1RegExp = /[^\x20-\x7e\xa0-\xff]/g
 
/**
 * RegExp to match quoted-pair in RFC 2616
 *
 * quoted-pair = "\" CHAR
 * CHAR        = <any US-ASCII character (octets 0 - 127)>
 */
 
var qescRegExp = /\\([\u0000-\u007f])/g;
 
/**
 * RegExp to match chars that must be quoted-pair in RFC 2616
 */
 
var quoteRegExp = /([\\"])/g
 
/**
 * RegExp for various RFC 2616 grammar
 *
 * parameter     = token "=" ( token | quoted-string )
 * token         = 1*<any CHAR except CTLs or separators>
 * separators    = "(" | ")" | "<" | ">" | "@"
 *               | "," | ";" | ":" | "\" | <">
 *               | "/" | "[" | "]" | "?" | "="
 *               | "{" | "}" | SP | HT
 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
 * qdtext        = <any TEXT except <">>
 * quoted-pair   = "\" CHAR
 * CHAR          = <any US-ASCII character (octets 0 - 127)>
 * TEXT          = <any OCTET except CTLs, but including LWS>
 * LWS           = [CRLF] 1*( SP | HT )
 * CRLF          = CR LF
 * CR            = <US-ASCII CR, carriage return (13)>
 * LF            = <US-ASCII LF, linefeed (10)>
 * SP            = <US-ASCII SP, space (32)>
 * HT            = <US-ASCII HT, horizontal-tab (9)>
 * CTL           = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
 * OCTET         = <any 8-bit sequence of data>
 */
 
var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g
var textRegExp = /^[\x20-\x7e\x80-\xff]+$/
var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/
 
/**
 * RegExp for various RFC 5987 grammar
 *
 * ext-value     = charset  "'" [ language ] "'" value-chars
 * charset       = "UTF-8" / "ISO-8859-1" / mime-charset
 * mime-charset  = 1*mime-charsetc
 * mime-charsetc = ALPHA / DIGIT
 *               / "!" / "#" / "$" / "%" / "&"
 *               / "+" / "-" / "^" / "_" / "`"
 *               / "{" / "}" / "~"
 * language      = ( 2*3ALPHA [ extlang ] )
 *               / 4ALPHA
 *               / 5*8ALPHA
 * extlang       = *3( "-" 3ALPHA )
 * value-chars   = *( pct-encoded / attr-char )
 * pct-encoded   = "%" HEXDIG HEXDIG
 * attr-char     = ALPHA / DIGIT
 *               / "!" / "#" / "$" / "&" / "+" / "-" / "."
 *               / "^" / "_" / "`" / "|" / "~"
 */
 
var extValueRegExp = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+\-\.^_`|~])+)$/
 
/**
 * RegExp for various RFC 6266 grammar
 *
 * disposition-type = "inline" | "attachment" | disp-ext-type
 * disp-ext-type    = token
 * disposition-parm = filename-parm | disp-ext-parm
 * filename-parm    = "filename" "=" value
 *                  | "filename*" "=" ext-value
 * disp-ext-parm    = token "=" value
 *                  | ext-token "=" ext-value
 * ext-token        = <the characters in token, followed by "*">
 */
 
var dispositionTypeRegExp = /^([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *(?:$|;)/
 
/**
 * Create an attachment Content-Disposition header.
 *
 * @param {string} [filename]
 * @param {object} [options]
 * @param {string} [options.type=attachment]
 * @param {string|boolean} [options.fallback=true]
 * @return {string}
 * @api public
 */
 
function contentDisposition(filename, options) {
  var opts = options || {}
 
  // get type
  var type = opts.type || 'attachment'
 
  // get parameters
  var params = createparams(filename, opts.fallback)
 
  // format into string
  return format(new ContentDisposition(type, params))
}
 
/**
 * Create parameters object from filename and fallback.
 *
 * @param {string} [filename]
 * @param {string|boolean} [fallback=true]
 * @return {object}
 * @api private
 */
 
function createparams(filename, fallback) {
  if (filename === undefined) {
    return
  }
 
  var params = {}
 
  if (typeof filename !== 'string') {
    throw new TypeError('filename must be a string')
  }
 
  // fallback defaults to true
  if (fallback === undefined) {
    fallback = true
  }
 
  if (typeof fallback !== 'string' && typeof fallback !== 'boolean') {
    throw new TypeError('fallback must be a string or boolean')
  }
 
  if (typeof fallback === 'string' && nonLatin1RegExp.test(fallback)) {
    throw new TypeError('fallback must be ISO-8859-1 string')
  }
 
  // restrict to file base name
  var name = basename(filename)
 
  // determine if name is suitable for quoted string
  var isQuotedString = textRegExp.test(name)
 
  // generate fallback name
  var fallbackName = typeof fallback !== 'string'
    ? fallback && getlatin1(name)
    : basename(fallback)
  var hasFallback = typeof fallbackName === 'string' && fallbackName !== name
 
  // set extended filename parameter
  if (hasFallback || !isQuotedString || hexEscapeRegExp.test(name)) {
    params['filename*'] = name
  }
 
  // set filename parameter
  if (isQuotedString || hasFallback) {
    params.filename = hasFallback
      ? fallbackName
      : name
  }
 
  return params
}
 
/**
 * Format object to Content-Disposition header.
 *
 * @param {object} obj
 * @param {string} obj.type
 * @param {object} [obj.parameters]
 * @return {string}
 * @api private
 */
 
function format(obj) {
  var parameters = obj.parameters
  var type = obj.type
 
  if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) {
    throw new TypeError('invalid type')
  }
 
  // start with normalized type
  var string = String(type).toLowerCase()
 
  // append parameters
  if (parameters && typeof parameters === 'object') {
    var param
    var params = Object.keys(parameters).sort()
 
    for (var i = 0; i < params.length; i++) {
      param = params[i]
 
      var val = param.substr(-1) === '*'
        ? ustring(parameters[param])
        : qstring(parameters[param])
 
      string += '; ' + param + '=' + val
    }
  }
 
  return string
}
 
/**
 * Decode a RFC 6987 field value (gracefully).
 *
 * @param {string} str
 * @return {string}
 * @api private
 */
 
function decodefield(str) {
  var match = extValueRegExp.exec(str)
 
  if (!match) {
    throw new TypeError('invalid extended field value')
  }
 
  var charset = match[1].toLowerCase()
  var encoded = match[2]
  var value
 
  // to binary string
  var binary = encoded.replace(hexEscapeReplaceRegExp, pdecode)
 
  switch (charset) {
    case 'iso-8859-1':
      value = getlatin1(binary)
      break
    case 'utf-8':
      value = new Buffer(binary, 'binary').toString('utf8')
      break
    default:
      throw new TypeError('unsupported charset in extended field')
  }
 
  return value
}
 
/**
 * Get ISO-8859-1 version of string.
 *
 * @param {string} val
 * @return {string}
 * @api private
 */
 
function getlatin1(val) {
  // simple Unicode -> ISO-8859-1 transformation
  return String(val).replace(nonLatin1RegExp, '?')
}
 
/**
 * Parse Content-Disposition header string.
 *
 * @param {string} string
 * @return {object}
 * @api private
 */
 
function parse(string) {
  if (!string || typeof string !== 'string') {
    throw new TypeError('argument string is required')
  }
 
  var match = dispositionTypeRegExp.exec(string)
 
  if (!match) {
    throw new TypeError('invalid type format')
  }
 
  // normalize type
  var index = match[0].length
  var type = match[1].toLowerCase()
 
  var key
  var names = []
  var params = {}
  var value
 
  // calculate index to start at
  index = paramRegExp.lastIndex = match[0].substr(-1) === ';'
    ? index - 1
    : index
 
  // match parameters
  while (match = paramRegExp.exec(string)) {
    if (match.index !== index) {
      throw new TypeError('invalid parameter format')
    }
 
    index += match[0].length
    key = match[1].toLowerCase()
    value = match[2]
 
    if (names.indexOf(key) !== -1) {
      throw new TypeError('invalid duplicate parameter')
    }
 
    names.push(key)
 
    if (key.indexOf('*') + 1 === key.length) {
      // decode extended value
      key = key.slice(0, -1)
      value = decodefield(value)
 
      // overwrite existing value
      params[key] = value
      continue
    }
 
    if (typeof params[key] === 'string') {
      continue
    }
 
    if (value[0] === '"') {
      // remove quotes and escapes
      value = value
        .substr(1, value.length - 2)
        .replace(qescRegExp, '$1')
    }
 
    params[key] = value
  }
 
  if (index !== -1 && index !== string.length) {
    throw new TypeError('invalid parameter format')
  }
 
  return new ContentDisposition(type, params)
}
 
/**
 * Percent decode a single character.
 *
 * @param {string} str
 * @param {string} hex
 * @return {string}
 * @api private
 */
 
function pdecode(str, hex) {
  return String.fromCharCode(parseInt(hex, 16))
}
 
/**
 * Percent encode a single character.
 *
 * @param {string} char
 * @return {string}
 * @api private
 */
 
function pencode(char) {
  var hex = String(char)
    .charCodeAt(0)
    .toString(16)
    .toUpperCase()
  return hex.length === 1
    ? '%0' + hex
    : '%' + hex
}
 
/**
 * Quote a string for HTTP.
 *
 * @param {string} val
 * @return {string}
 * @api private
 */
 
function qstring(val) {
  var str = String(val)
 
  return '"' + str.replace(quoteRegExp, '\\$1') + '"'
}
 
/**
 * Encode a Unicode string for HTTP (RFC 5987).
 *
 * @param {string} val
 * @return {string}
 * @api private
 */
 
function ustring(val) {
  var str = String(val)
 
  // percent encode as UTF-8
  var encoded = encodeURIComponent(str)
    .replace(encodeUriAttrCharRegExp, pencode)
 
  return 'UTF-8\'\'' + encoded
}
 
/**
 * Class for parsed Content-Disposition header for v8 optimization
 */
 
function ContentDisposition(type, parameters) {
  this.type = type
  this.parameters = parameters
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie-signature/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie-signature/

Statements: 25% (4 / 16)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 33.33% (4 / 12)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie-signature/
File Statements Branches Functions Lines
index.js 25% (4 / 16) 0% (0 / 10) 0% (0 / 3) 33.33% (4 / 12)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie-signature/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie-signature/index.js

Statements: 25% (4 / 16)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 33.33% (4 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53        1                     1                                       1                         1        
/**
 * Module dependencies.
 */
 
var crypto = require('crypto');
 
/**
 * Sign the given `val` with `secret`.
 *
 * @param {String} val
 * @param {String} secret
 * @return {String}
 * @api private
 */
 
exports.sign = function(val, secret){
  if ('string' != typeof val) throw new TypeError('cookie required');
  if ('string' != typeof secret) throw new TypeError('secret required');
  return val + '.' + crypto
    .createHmac('sha256', secret)
    .update(val)
    .digest('base64')
    .replace(/\=+$/, '');
};
 
/**
 * Unsign and decode the given `val` with `secret`,
 * returning `false` if the signature is invalid.
 *
 * @param {String} val
 * @param {String} secret
 * @return {String|Boolean}
 * @api private
 */
 
exports.unsign = function(val, secret){
  if ('string' != typeof val) throw new TypeError('cookie required');
  if ('string' != typeof secret) throw new TypeError('secret required');
  var str = val.slice(0, val.lastIndexOf('.'))
    , mac = exports.sign(str, secret);
  
  return sha1(mac) == sha1(val) ? str : false;
};
 
/**
 * Private
 */
 
function sha1(str){
  return crypto.createHash('sha1').update(str).digest('hex');
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie/

Statements: 14.29% (6 / 42)      Branches: 0% (0 / 28)      Functions: 0% (0 / 3)      Lines: 16.67% (6 / 36)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie/
File Statements Branches Functions Lines
index.js 14.29% (6 / 42) 0% (0 / 28) 0% (0 / 3) 16.67% (6 / 36)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/cookie/index.js

Statements: 14.29% (6 / 42)      Branches: 0% (0 / 28)      Functions: 0% (0 / 3)      Lines: 16.67% (6 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                      1                                               1                                                                     1 1   1 1    
 
/// Serialize the a name value pair into a cookie string suitable for
/// http headers. An optional options object specified cookie parameters
///
/// serialize('foo', 'bar', { httpOnly: true })
///   => "foo=bar; httpOnly"
///
/// @param {String} name
/// @param {String} val
/// @param {Object} options
/// @return {String}
var serialize = function(name, val, opt){
    opt = opt || {};
    var enc = opt.encode || encode;
    var pairs = [name + '=' + enc(val)];
 
    if (null != opt.maxAge) {
        var maxAge = opt.maxAge - 0;
        if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
        pairs.push('Max-Age=' + maxAge);
    }
 
    if (opt.domain) pairs.push('Domain=' + opt.domain);
    if (opt.path) pairs.push('Path=' + opt.path);
    if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString());
    if (opt.httpOnly) pairs.push('HttpOnly');
    if (opt.secure) pairs.push('Secure');
 
    return pairs.join('; ');
};
 
/// Parse the given cookie header string into an object
/// The object has the various cookies as keys(names) => values
/// @param {String} str
/// @return {Object}
var parse = function(str, opt) {
    opt = opt || {};
    var obj = {}
    var pairs = str.split(/; */);
    var dec = opt.decode || decode;
 
    pairs.forEach(function(pair) {
        var eq_idx = pair.indexOf('=')
 
        // skip things that don't look like key=value
        if (eq_idx < 0) {
            return;
        }
 
        var key = pair.substr(0, eq_idx).trim()
        var val = pair.substr(++eq_idx, pair.length).trim();
 
        // quoted values
        if ('"' == val[0]) {
            val = val.slice(1, -1);
        }
 
        // only assign once
        if (undefined == obj[key]) {
            try {
                obj[key] = dec(val);
            } catch (e) {
                obj[key] = val;
            }
        }
    });
 
    return obj;
};
 
var encode = encodeURIComponent;
var decode = decodeURIComponent;
 
module.exports.serialize = serialize;
module.exports.parse = parse;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/

Statements: 40.14% (57 / 142)      Branches: 14.71% (10 / 68)      Functions: 27.78% (5 / 18)      Lines: 40.88% (56 / 137)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/
File Statements Branches Functions Lines
debug.js 43.59% (34 / 78) 11.43% (4 / 35) 33.33% (3 / 9) 45.21% (33 / 73)
node.js 35.94% (23 / 64) 18.18% (6 / 33) 22.22% (2 / 9) 35.94% (23 / 64)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/debug.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/debug.js

Statements: 43.59% (34 / 78)      Branches: 11.43% (4 / 35)      Functions: 33.33% (3 / 9)      Lines: 45.21% (33 / 73)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199                1 1 1 1 1 1           1 1               1           1           1                 1                       1     1   7     1                                                                                                 7   7   7   7                     1 1   1 1   1 1                               1                       1 7 7         7         7                     1          
 
/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 *
 * Expose `debug()` as the module.
 */
 
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
 
/**
 * The currently active debug mode names, and names to skip.
 */
 
exports.names = [];
exports.skips = [];
 
/**
 * Map of special "%n" handling functions, for the debug "format" argument.
 *
 * Valid key names are a single, lowercased letter, i.e. "n".
 */
 
exports.formatters = {};
 
/**
 * Previously assigned color.
 */
 
var prevColor = 0;
 
/**
 * Previous log timestamp.
 */
 
var prevTime;
 
/**
 * Select a color.
 *
 * @return {Number}
 * @api private
 */
 
function selectColor() {
  return exports.colors[prevColor++ % exports.colors.length];
}
 
/**
 * Create a debugger with the given `namespace`.
 *
 * @param {String} namespace
 * @return {Function}
 * @api public
 */
 
function debug(namespace) {
 
  // define the `disabled` version
  function disabled() {
  }
  disabled.enabled = false;
 
  // define the `enabled` version
  function enabled() {
 
    var self = enabled;
 
    // set `diff` timestamp
    var curr = +new Date();
    var ms = curr - (prevTime || curr);
    self.diff = ms;
    self.prev = prevTime;
    self.curr = curr;
    prevTime = curr;
 
    // add the `color` if not set
    if (null == self.useColors) self.useColors = exports.useColors();
    if (null == self.color && self.useColors) self.color = selectColor();
 
    var args = Array.prototype.slice.call(arguments);
 
    args[0] = exports.coerce(args[0]);
 
    if ('string' !== typeof args[0]) {
      // anything else let's inspect with %o
      args = ['%o'].concat(args);
    }
 
    // apply any `formatters` transformations
    var index = 0;
    args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
      // if we encounter an escaped % then don't increase the array index
      if (match === '%%') return match;
      index++;
      var formatter = exports.formatters[format];
      if ('function' === typeof formatter) {
        var val = args[index];
        match = formatter.call(self, val);
 
        // now we need to remove `args[index]` since it's inlined in the `format`
        args.splice(index, 1);
        index--;
      }
      return match;
    });
 
    if ('function' === typeof exports.formatArgs) {
      args = exports.formatArgs.apply(self, args);
    }
    var logFn = enabled.log || exports.log || console.log.bind(console);
    logFn.apply(self, args);
  }
  enabled.enabled = true;
 
  var fn = exports.enabled(namespace) ? enabled : disabled;
 
  fn.namespace = namespace;
 
  return fn;
}
 
/**
 * Enables a debug mode by namespaces. This can include modes
 * separated by a colon and wildcards.
 *
 * @param {String} namespaces
 * @api public
 */
 
function enable(namespaces) {
  exports.save(namespaces);
 
  var split = (namespaces || '').split(/[\s,]+/);
  var len = split.length;
 
  for (var i = 0; i < len; i++) {
    Eif (!split[i]) continue; // ignore empty strings
    namespaces = split[i].replace(/\*/g, '.*?');
    if (namespaces[0] === '-') {
      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
    } else {
      exports.names.push(new RegExp('^' + namespaces + '$'));
    }
  }
}
 
/**
 * Disable debug output.
 *
 * @api public
 */
 
function disable() {
  exports.enable('');
}
 
/**
 * Returns true if the given mode name is enabled, false otherwise.
 *
 * @param {String} name
 * @return {Boolean}
 * @api public
 */
 
function enabled(name) {
  var i, len;
  for (i = 0, len = exports.skips.length; i < len; i++) {
    if (exports.skips[i].test(name)) {
      return false;
    }
  }
  for (i = 0, len = exports.names.length; i < len; i++) {
    if (exports.names[i].test(name)) {
      return true;
    }
  }
  return false;
}
 
/**
 * Coerce `val`.
 *
 * @param {Mixed} val
 * @return {Mixed}
 * @api private
 */
 
function coerce(val) {
  if (val instanceof Error) return val.stack || val.message;
  return val;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node.js

Statements: 35.94% (23 / 64)      Branches: 18.18% (6 / 33)      Functions: 22.22% (2 / 9)      Lines: 35.94% (23 / 64)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211          1 1               1 1 1 1 1 1           1                 1 1               1                               1                     1                     1                                             1                     1 1     1                         1 1                   1                                                                                                                                 1    
 
/**
 * Module dependencies.
 */
 
var tty = require('tty');
var util = require('util');
 
/**
 * This is the Node.js implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */
 
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
 
/**
 * Colors.
 */
 
exports.colors = [6, 2, 3, 4, 5, 1];
 
/**
 * The file descriptor to write the `debug()` calls to.
 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
 *
 *   $ DEBUG_FD=3 node script.js 3>debug.log
 */
 
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
var stream = 1 === fd ? process.stdout :
             2 === fd ? process.stderr :
             createWritableStdioStream(fd);
 
/**
 * Is stdout a TTY? Colored output is enabled when `true`.
 */
 
function useColors() {
  var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase();
  if (0 === debugColors.length) {
    return tty.isatty(fd);
  } else {
    return '0' !== debugColors
        && 'no' !== debugColors
        && 'false' !== debugColors
        && 'disabled' !== debugColors;
  }
}
 
/**
 * Map %o to `util.inspect()`, since Node doesn't do that out of the box.
 */
 
var inspect = (4 === util.inspect.length ?
  // node <= 0.8.x
  function (v, colors) {
    return util.inspect(v, void 0, void 0, colors);
  } :
  // node > 0.8.x
  function (v, colors) {
    return util.inspect(v, { colors: colors });
  }
);
 
exports.formatters.o = function(v) {
  return inspect(v, this.useColors)
    .replace(/\s*\n\s*/g, ' ');
};
 
/**
 * Adds ANSI color escape codes if enabled.
 *
 * @api public
 */
 
function formatArgs() {
  var args = arguments;
  var useColors = this.useColors;
  var name = this.namespace;
 
  if (useColors) {
    var c = this.color;
 
    args[0] = '  \u001b[3' + c + ';1m' + name + ' '
      + '\u001b[0m'
      + args[0] + '\u001b[3' + c + 'm'
      + ' +' + exports.humanize(this.diff) + '\u001b[0m';
  } else {
    args[0] = new Date().toUTCString()
      + ' ' + name + ' ' + args[0];
  }
  return args;
}
 
/**
 * Invokes `console.error()` with the specified arguments.
 */
 
function log() {
  return stream.write(util.format.apply(this, arguments) + '\n');
}
 
/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */
 
function save(namespaces) {
  Eif (null == namespaces) {
    // If you set a process.env field to null or undefined, it gets cast to the
    // string 'null' or 'undefined'. Just delete instead.
    delete process.env.DEBUG;
  } else {
    process.env.DEBUG = namespaces;
  }
}
 
/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */
 
function load() {
  return process.env.DEBUG;
}
 
/**
 * Copied from `node/src/node.js`.
 *
 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
 */
 
function createWritableStdioStream (fd) {
  var stream;
  var tty_wrap = process.binding('tty_wrap');
 
  // Note stream._type is used for test-module-load-list.js
 
  switch (tty_wrap.guessHandleType(fd)) {
    case 'TTY':
      stream = new tty.WriteStream(fd);
      stream._type = 'tty';
 
      // Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;
 
    case 'FILE':
      var fs = require('fs');
      stream = new fs.SyncWriteStream(fd, { autoClose: false });
      stream._type = 'fs';
      break;
 
    case 'PIPE':
    case 'TCP':
      var net = require('net');
      stream = new net.Socket({
        fd: fd,
        readable: false,
        writable: true
      });
 
      // FIXME Should probably have an option in net.Socket to create a
      // stream from an existing fd which is writable only. But for now
      // we'll just add this hack and set the `readable` member to false.
      // Test: ./node test/fixtures/echo.js < /etc/passwd
      stream.readable = false;
      stream.read = null;
      stream._type = 'pipe';
 
      // FIXME Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;
 
    default:
      // Probably an error on in uv_guess_handle()
      throw new Error('Implement me. Unknown stream file type!');
  }
 
  // For supporting legacy API we put the FD here.
  stream.fd = fd;
 
  stream._isStdio = true;
 
  return stream;
}
 
/**
 * Enable namespaces listed in `process.env.DEBUG` initially.
 */
 
exports.enable(load());
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node_modules/ms/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node_modules/ms/

Statements: 24.39% (10 / 41)      Branches: 0% (0 / 55)      Functions: 0% (0 / 5)      Lines: 30.3% (10 / 33)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node_modules/ms/
File Statements Branches Functions Lines
index.js 24.39% (10 / 41) 0% (0 / 55) 0% (0 / 5) 30.3% (10 / 33)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node_modules/ms/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/debug/node_modules/ms/index.js

Statements: 24.39% (10 / 41)      Branches: 0% (0 / 55)      Functions: 0% (0 / 5)      Lines: 30.3% (10 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125        1 1 1 1 1                             1                               1                                                                                                     1                               1                       1            
/**
 * Helpers.
 */
 
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
 
/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} options
 * @return {String|Number}
 * @api public
 */
 
module.exports = function(val, options){
  options = options || {};
  if ('string' == typeof val) return parse(val);
  return options.long
    ? long(val)
    : short(val);
};
 
/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */
 
function parse(str) {
  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  if (!match) return;
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
  }
}
 
/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function short(ms) {
  if (ms >= d) return Math.round(ms / d) + 'd';
  if (ms >= h) return Math.round(ms / h) + 'h';
  if (ms >= m) return Math.round(ms / m) + 'm';
  if (ms >= s) return Math.round(ms / s) + 's';
  return ms + 'ms';
}
 
/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function long(ms) {
  return plural(ms, d, 'day')
    || plural(ms, h, 'hour')
    || plural(ms, m, 'minute')
    || plural(ms, s, 'second')
    || ms + ' ms';
}
 
/**
 * Pluralization helper.
 */
 
function plural(ms, n, name) {
  if (ms < n) return;
  if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  return Math.ceil(ms / n) + ' ' + name + 's';
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/

Statements: 39.34% (83 / 211)      Branches: 15.79% (15 / 95)      Functions: 38.46% (10 / 26)      Lines: 39.42% (82 / 208)      Ignored: 3 statements, 1 function, 3 branches     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/
File Statements Branches Functions Lines
index.js 39.34% (83 / 211) 15.79% (15 / 95) 38.46% (10 / 26) 39.42% (82 / 208)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/index.js

Statements: 39.34% (83 / 211)      Branches: 15.79% (15 / 95)      Functions: 38.46% (10 / 26)      Lines: 39.42% (82 / 208)      Ignored: 3 statements, 1 function, 3 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531                    1 1 1           1           1             1 1           1 4   4   4 4               4             1                                           1 6   6 6     6             1                                   1 2       2 2 2   1         2 2 2 2 2   2 2   2             1   2   1     2     2             1   2   1     2     2             1                                                                                                                                                                 1 8 8 8   8       8   8 8   8             1                                                             1                                                     1                                                 1                   1 8 8 8   8 8     8     8   8 8   8             1 8             1 6       6 6 6 6   6   6           6             1                                                                                                         1                                                                                                
/*!
 * depd
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 */
 
var callSiteToString = require('./lib/compat').callSiteToString
var EventEmitter = require('events').EventEmitter
var relative = require('path').relative
 
/**
 * Module exports.
 */
 
module.exports = depd
 
/**
 * Get the path to base files on.
 */
 
var basePath = process.cwd()
 
/**
 * Get listener count on event emitter.
 */
 
/*istanbul ignore next*/
var eventListenerCount = EventEmitter.listenerCount
  || function (emitter, type) { return emitter.listeners(type).length }
 
/**
 * Determine if namespace is contained in the string.
 */
 
function containsNamespace(str, namespace) {
  var val = str.split(/[ ,]+/)
 
  namespace = String(namespace).toLowerCase()
 
  for (var i = 0 ; i < val.length; i++) {
    Eif (!(str = val[i])) continue;
 
    // namespace contained
    if (str === '*' || str.toLowerCase() === namespace) {
      return true
    }
  }
 
  return false
}
 
/**
 * Convert a data descriptor to accessor descriptor.
 */
 
function convertDataDescriptorToAccessor(obj, prop, message) {
  var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
  var value = descriptor.value
 
  descriptor.get = function getter() { return value }
 
  if (descriptor.writable) {
    descriptor.set = function setter(val) { return value = val }
  }
 
  delete descriptor.value
  delete descriptor.writable
 
  Object.defineProperty(obj, prop, descriptor)
 
  return descriptor
}
 
/**
 * Create arguments string to keep arity.
 */
 
function createArgumentsString(arity) {
  var str = ''
 
  for (var i = 0; i < arity; i++) {
    str += ', arg' + i
  }
 
  return str.substr(2)
}
 
/**
 * Create stack string from stack.
 */
 
function createStackString(stack) {
  var str = this.name + ': ' + this.namespace
 
  if (this.message) {
    str += ' deprecated ' + this.message
  }
 
  for (var i = 0; i < stack.length; i++) {
    str += '\n    at ' + callSiteToString(stack[i])
  }
 
  return str
}
 
/**
 * Create deprecate for namespace in caller.
 */
 
function depd(namespace) {
  Iif (!namespace) {
    throw new TypeError('argument namespace is required')
  }
 
  var stack = getStack()
  var site = callSiteLocation(stack[1])
  var file = site[0]
 
  function deprecate(message) {
    // call to self as log
    log.call(deprecate, message)
  }
 
  deprecate._file = file
  deprecate._ignored = isignored(namespace)
  deprecate._namespace = namespace
  deprecate._traced = istraced(namespace)
  deprecate._warned = Object.create(null)
 
  deprecate.function = wrapfunction
  deprecate.property = wrapproperty
 
  return deprecate
}
 
/**
 * Determine if namespace is ignored.
 */
 
function isignored(namespace) {
  /* istanbul ignore next: tested in a child processs */
  Iif (process.noDeprecation) {
    // --no-deprecation support
    return true
  }
 
  var str = process.env.NO_DEPRECATION || ''
 
  // namespace ignored
  return containsNamespace(str, namespace)
}
 
/**
 * Determine if namespace is traced.
 */
 
function istraced(namespace) {
  /* istanbul ignore next: tested in a child processs */
  Iif (process.traceDeprecation) {
    // --trace-deprecation support
    return true
  }
 
  var str = process.env.TRACE_DEPRECATION || ''
 
  // namespace traced
  return containsNamespace(str, namespace)
}
 
/**
 * Display deprecation message.
 */
 
function log(message, site) {
  var haslisteners = eventListenerCount(process, 'deprecation') !== 0
 
  // abort early if no destination
  if (!haslisteners && this._ignored) {
    return
  }
 
  var caller
  var callFile
  var callSite
  var i = 0
  var seen = false
  var stack = getStack()
  var file = this._file
 
  if (site) {
    // provided site
    callSite = callSiteLocation(stack[1])
    callSite.name = site.name
    file = callSite[0]
  } else {
    // get call site
    i = 2
    site = callSiteLocation(stack[i])
    callSite = site
  }
 
  // get caller of deprecated thing in relation to file
  for (; i < stack.length; i++) {
    caller = callSiteLocation(stack[i])
    callFile = caller[0]
 
    if (callFile === file) {
      seen = true
    } else if (callFile === this._file) {
      file = this._file
    } else if (seen) {
      break
    }
  }
 
  var key = caller
    ? site.join(':') + '__' + caller.join(':')
    : undefined
 
  if (key !== undefined && key in this._warned) {
    // already warned
    return
  }
 
  this._warned[key] = true
 
  // generate automatic message from call site
  if (!message) {
    message = callSite === site || !callSite.name
      ? defaultMessage(site)
      : defaultMessage(callSite)
  }
 
  // emit deprecation if listeners exist
  if (haslisteners) {
    var err = DeprecationError(this._namespace, message, stack.slice(i))
    process.emit('deprecation', err)
    return
  }
 
  // format and write message
  var format = process.stderr.isTTY
    ? formatColor
    : formatPlain
  var msg = format.call(this, message, caller, stack.slice(i))
  process.stderr.write(msg + '\n', 'utf8')
 
  return
}
 
/**
 * Get call site location as array.
 */
 
function callSiteLocation(callSite) {
  var file = callSite.getFileName() || '<anonymous>'
  var line = callSite.getLineNumber()
  var colm = callSite.getColumnNumber()
 
  Iif (callSite.isEval()) {
    file = callSite.getEvalOrigin() + ', ' + file
  }
 
  var site = [file, line, colm]
 
  site.callSite = callSite
  site.name = callSite.getFunctionName()
 
  return site
}
 
/**
 * Generate a default message from the site.
 */
 
function defaultMessage(site) {
  var callSite = site.callSite
  var funcName = site.name
 
  // make useful anonymous name
  if (!funcName) {
    funcName = '<anonymous@' + formatLocation(site) + '>'
  }
 
  var context = callSite.getThis()
  var typeName = context && callSite.getTypeName()
 
  // ignore useless type name
  if (typeName === 'Object') {
    typeName = undefined
  }
 
  // make useful type name
  if (typeName === 'Function') {
    typeName = context.name || typeName
  }
 
  return typeName && callSite.getMethodName()
    ? typeName + '.' + funcName
    : funcName
}
 
/**
 * Format deprecation message without color.
 */
 
function formatPlain(msg, caller, stack) {
  var timestamp = new Date().toUTCString()
 
  var formatted = timestamp
    + ' ' + this._namespace
    + ' deprecated ' + msg
 
  // add stack trace
  if (this._traced) {
    for (var i = 0; i < stack.length; i++) {
      formatted += '\n    at ' + callSiteToString(stack[i])
    }
 
    return formatted
  }
 
  if (caller) {
    formatted += ' at ' + formatLocation(caller)
  }
 
  return formatted
}
 
/**
 * Format deprecation message with color.
 */
 
function formatColor(msg, caller, stack) {
  var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' // bold cyan
    + ' \x1b[33;1mdeprecated\x1b[22;39m' // bold yellow
    + ' \x1b[0m' + msg + '\x1b[39m' // reset
 
  // add stack trace
  if (this._traced) {
    for (var i = 0; i < stack.length; i++) {
      formatted += '\n    \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan
    }
 
    return formatted
  }
 
  if (caller) {
    formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan
  }
 
  return formatted
}
 
/**
 * Format call site location.
 */
 
function formatLocation(callSite) {
  return relative(basePath, callSite[0])
    + ':' + callSite[1]
    + ':' + callSite[2]
}
 
/**
 * Get the stack as array of call sites.
 */
 
function getStack() {
  var limit = Error.stackTraceLimit
  var obj = {}
  var prep = Error.prepareStackTrace
 
  Error.prepareStackTrace = prepareObjectStackTrace
  Error.stackTraceLimit = Math.max(10, limit)
 
  // capture the stack
  Error.captureStackTrace(obj)
 
  // slice this function off the top
  var stack = obj.stack.slice(1)
 
  Error.prepareStackTrace = prep
  Error.stackTraceLimit = limit
 
  return stack
}
 
/**
 * Capture call site stack from v8.
 */
 
function prepareObjectStackTrace(obj, stack) {
  return stack
}
 
/**
 * Return a wrapped function in a deprecation message.
 */
 
function wrapfunction(fn, message) {
  Iif (typeof fn !== 'function') {
    throw new TypeError('argument fn must be a function')
  }
 
  var args = createArgumentsString(fn.length)
  var deprecate = this
  var stack = getStack()
  var site = callSiteLocation(stack[1])
 
  site.name = fn.name
 
  var deprecatedfn = eval('(function (' + args + ') {\n'
    + '"use strict"\n'
    + 'log.call(deprecate, message, site)\n'
    + 'return fn.apply(this, arguments)\n'
    + '})')
 
  return deprecatedfn
}
 
/**
 * Wrap property in a deprecation message.
 */
 
function wrapproperty(obj, prop, message) {
  if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
    throw new TypeError('argument obj must be object')
  }
 
  var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
 
  if (!descriptor) {
    throw new TypeError('must call property on owner object')
  }
 
  if (!descriptor.configurable) {
    throw new TypeError('property must be configurable')
  }
 
  var deprecate = this
  var stack = getStack()
  var site = callSiteLocation(stack[1])
 
  // set site name
  site.name = prop
 
  // convert data descriptor
  if ('value' in descriptor) {
    descriptor = convertDataDescriptorToAccessor(obj, prop, message)
  }
 
  var get = descriptor.get
  var set = descriptor.set
 
  // wrap getter
  if (typeof get === 'function') {
    descriptor.get = function getter() {
      log.call(deprecate, message, site)
      return get.apply(this, arguments)
    }
  }
 
  // wrap setter
  if (typeof set === 'function') {
    descriptor.set = function setter() {
      log.call(deprecate, message, site)
      return set.apply(this, arguments)
    }
  }
 
  Object.defineProperty(obj, prop, descriptor)
}
 
/**
 * Create DeprecationError for deprecation
 */
 
function DeprecationError(namespace, message, stack) {
  var error = new Error()
  var stackString
 
  Object.defineProperty(error, 'constructor', {
    value: DeprecationError
  })
 
  Object.defineProperty(error, 'message', {
    configurable: true,
    enumerable: false,
    value: message,
    writable: true
  })
 
  Object.defineProperty(error, 'name', {
    enumerable: false,
    configurable: true,
    value: 'DeprecationError',
    writable: true
  })
 
  Object.defineProperty(error, 'namespace', {
    configurable: true,
    enumerable: false,
    value: namespace,
    writable: true
  })
 
  Object.defineProperty(error, 'stack', {
    configurable: true,
    enumerable: false,
    get: function () {
      if (stackString !== undefined) {
        return stackString
      }
 
      // prepare stack trace
      return stackString = createStackString.call(this, stack)
    },
    set: function setter(val) {
      stackString = val
    }
  })
 
  return error
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/lib/compat/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/lib/compat/

Statements: 91.3% (21 / 23)      Branches: 25% (1 / 4)      Functions: 66.67% (4 / 6)      Lines: 91.3% (21 / 23)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/lib/compat/
File Statements Branches Functions Lines
index.js 91.3% (21 / 23) 25% (1 / 4) 66.67% (4 / 6) 91.3% (21 / 23)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/lib/compat/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/depd/lib/compat/index.js

Statements: 91.3% (21 / 23)      Branches: 25% (1 / 4)      Functions: 66.67% (4 / 6)      Lines: 91.3% (21 / 23)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                    1       1 1 1 1   1 1     1 1     1     1   1 1   1             1 1 1   1           1     2                     1        
/*!
 * depd
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
lazyProperty(module.exports, 'bufferConcat', function bufferConcat() {
  return Buffer.concat || require('./buffer-concat')
})
 
lazyProperty(module.exports, 'callSiteToString', function callSiteToString() {
  var limit = Error.stackTraceLimit
  var obj = {}
  var prep = Error.prepareStackTrace
 
  function prepareObjectStackTrace(obj, stack) {
    return stack
  }
 
  Error.prepareStackTrace = prepareObjectStackTrace
  Error.stackTraceLimit = 2
 
  // capture the stack
  Error.captureStackTrace(obj)
 
  // slice the stack
  var stack = obj.stack.slice()
 
  Error.prepareStackTrace = prep
  Error.stackTraceLimit = limit
 
  return stack[0].toString ? toString : require('./callsite-tostring')
})
 
/**
 * Define a lazy property.
 */
 
function lazyProperty(obj, prop, getter) {
  function get() {
    var val = getter()
 
    Object.defineProperty(obj, prop, {
      configurable: true,
      enumerable: true,
      value: val
    })
 
    return val
  }
 
  Object.defineProperty(obj, prop, {
    configurable: true,
    enumerable: true,
    get: get
  })
}
 
/**
 * Call toString() on the obj
 */
 
function toString(obj) {
  return obj.toString()
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/escape-html/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/escape-html/

Statements: 50% (1 / 2)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/escape-html/
File Statements Branches Functions Lines
index.js 50% (1 / 2) 100% (0 / 0) 0% (0 / 1) 50% (1 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/escape-html/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/escape-html/index.js

Statements: 50% (1 / 2)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18                1                  
/**
 * Escape special characters in the given string of html.
 *
 * @param  {String} html
 * @return {String}
 * @api private
 */
 
module.exports = function(html) {
  return String(html)
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/

Statements: 28.57% (12 / 42)      Branches: 0% (0 / 42)      Functions: 0% (0 / 5)      Lines: 28.57% (12 / 42)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/
File Statements Branches Functions Lines
index.js 28.57% (12 / 42) 0% (0 / 42) 0% (0 / 5) 28.57% (12 / 42)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/index.js

Statements: 28.57% (12 / 42)      Branches: 0% (0 / 42)      Functions: 0% (0 / 5)      Lines: 28.57% (12 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                    1           1 1 1           1 1 1                       1                                                                       1                                                     1                                                       1                                       1                                              
/*!
 * etag
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = etag
 
/**
 * Module dependencies.
 */
 
var crc = require('crc').crc32
var crypto = require('crypto')
var Stats = require('fs').Stats
 
/**
 * Module variables.
 */
 
var crc32threshold = 1000 // 1KB
var NULL = new Buffer([0])
var toString = Object.prototype.toString
 
/**
 * Create a simple ETag.
 *
 * @param {string|Buffer|Stats} entity
 * @param {object} [options]
 * @param {boolean} [options.weak]
 * @return {String}
 * @api public
 */
 
function etag(entity, options) {
  if (entity == null) {
    throw new TypeError('argument entity is required')
  }
 
  var isStats = isstats(entity)
  var weak = options && typeof options.weak === 'boolean'
    ? options.weak
    : isStats
 
  // support fs.Stats object
  if (isStats) {
    return stattag(entity, weak)
  }
 
  if (typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
    throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
  }
 
  var hash = weak
    ? weakhash(entity)
    : stronghash(entity)
 
  return weak
    ? 'W/"' + hash + '"'
    : '"' + hash + '"'
}
 
/**
 * Determine if object is a Stats object.
 *
 * @param {object} obj
 * @return {boolean}
 * @api private
 */
 
function isstats(obj) {
  // not even an object
  if (obj === null || typeof obj !== 'object') {
    return false
  }
 
  // genuine fs.Stats
  if (obj instanceof Stats) {
    return true
  }
 
  // quack quack
  return 'atime' in obj && toString.call(obj.atime) === '[object Date]'
    && 'ctime' in obj && toString.call(obj.ctime) === '[object Date]'
    && 'mtime' in obj && toString.call(obj.mtime) === '[object Date]'
    && 'ino' in obj && typeof obj.ino === 'number'
    && 'size' in obj && typeof obj.size === 'number'
}
 
/**
 * Generate a tag for a stat.
 *
 * @param {Buffer} entity
 * @return {String}
 * @api private
 */
 
function stattag(stat, weak) {
  var mtime = stat.mtime.toISOString()
  var size = stat.size.toString(16)
 
  if (weak) {
    return 'W/"' + size + '-' + crc(mtime) + '"'
  }
 
  var hash = crypto
    .createHash('md5')
    .update('file', 'utf8')
    .update(NULL)
    .update(size, 'utf8')
    .update(NULL)
    .update(mtime, 'utf8')
    .digest('base64')
 
  return '"' + hash + '"'
}
 
/**
 * Generate a strong hash.
 *
 * @param {Buffer} entity
 * @return {String}
 * @api private
 */
 
function stronghash(entity) {
  if (entity.length === 0) {
    // fast-path empty
    return '1B2M2Y8AsgTpgAmY7PhCfg=='
  }
 
  return crypto
    .createHash('md5')
    .update(entity, 'utf8')
    .digest('base64')
}
 
/**
 * Generate a weak hash.
 *
 * @param {Buffer} entity
 * @return {String}
 * @api private
 */
 
function weakhash(entity) {
  if (entity.length === 0) {
    // fast-path empty
    return '0-0'
  }
 
  var len = typeof entity === 'string'
    ? Buffer.byteLength(entity, 'utf8')
    : entity.length
 
  if (len <= crc32threshold) {
    // crc32 plus length when it's fast
    // crc(str) only accepts utf-8 encoding
    return len.toString(16) + '-' + crc(entity).toString(16)
  }
 
  // use md4 for long strings
  return crypto
    .createHash('md4')
    .update(entity, 'utf8')
    .digest('base64')
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/

Statements: 47.66% (61 / 128)      Branches: 18.42% (7 / 38)      Functions: 10% (1 / 10)      Lines: 47.66% (61 / 128)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/
File Statements Branches Functions Lines
crc1.js 28.57% (4 / 14) 0% (0 / 2) 0% (0 / 1) 28.57% (4 / 14)
crc16.js 46.67% (7 / 15) 25% (1 / 4) 0% (0 / 1) 46.67% (7 / 15)
crc16_ccitt.js 46.67% (7 / 15) 16.67% (1 / 6) 0% (0 / 1) 46.67% (7 / 15)
crc16_modbus.js 46.67% (7 / 15) 16.67% (1 / 6) 0% (0 / 1) 46.67% (7 / 15)
crc24.js 46.67% (7 / 15) 16.67% (1 / 6) 0% (0 / 1) 46.67% (7 / 15)
crc32.js 46.67% (7 / 15) 16.67% (1 / 6) 0% (0 / 1) 46.67% (7 / 15)
crc8.js 46.67% (7 / 15) 25% (1 / 4) 0% (0 / 1) 46.67% (7 / 15)
crc8_1wire.js 46.67% (7 / 15) 25% (1 / 4) 0% (0 / 1) 46.67% (7 / 15)
create.js 87.5% (7 / 8) 100% (0 / 0) 50% (1 / 2) 87.5% (7 / 8)
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc1.js

Statements: 28.57% (4 / 14)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 28.57% (4 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23  1   1   1   1                              
// Generated by CoffeeScript 1.7.1
var Buffer, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
module.exports = create('crc1', function(buf, previous) {
  var accum, byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = ~~previous;
  accum = 0;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    accum += byte;
  }
  crc += accum % 256;
  return crc % 256;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16.js

Statements: 46.67% (7 / 15)      Branches: 25% (1 / 4)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('crc-16', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = ~~previous;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = (TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffff;
  }
  return crc;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_ccitt.js

Statements: 46.67% (7 / 15)      Branches: 16.67% (1 / 6)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('ccitt', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = previous != null ? ~~previous : 0xffff;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = (TABLE[((crc >> 8) ^ byte) & 0xff] ^ (crc << 8)) & 0xffff;
  }
  return crc;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc16_modbus.js

Statements: 46.67% (7 / 15)      Branches: 16.67% (1 / 6)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('crc-16-modbus', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = previous != null ? ~~previous : 0xffff;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = (TABLE[(crc ^ byte) & 0xff] ^ (crc >> 8)) & 0xffff;
  }
  return crc;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc24.js

Statements: 46.67% (7 / 15)      Branches: 16.67% (1 / 6)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x000000, 0x864cfb, 0x8ad50d, 0x0c99f6, 0x93e6e1, 0x15aa1a, 0x1933ec, 0x9f7f17, 0xa18139, 0x27cdc2, 0x2b5434, 0xad18cf, 0x3267d8, 0xb42b23, 0xb8b2d5, 0x3efe2e, 0xc54e89, 0x430272, 0x4f9b84, 0xc9d77f, 0x56a868, 0xd0e493, 0xdc7d65, 0x5a319e, 0x64cfb0, 0xe2834b, 0xee1abd, 0x685646, 0xf72951, 0x7165aa, 0x7dfc5c, 0xfbb0a7, 0x0cd1e9, 0x8a9d12, 0x8604e4, 0x00481f, 0x9f3708, 0x197bf3, 0x15e205, 0x93aefe, 0xad50d0, 0x2b1c2b, 0x2785dd, 0xa1c926, 0x3eb631, 0xb8faca, 0xb4633c, 0x322fc7, 0xc99f60, 0x4fd39b, 0x434a6d, 0xc50696, 0x5a7981, 0xdc357a, 0xd0ac8c, 0x56e077, 0x681e59, 0xee52a2, 0xe2cb54, 0x6487af, 0xfbf8b8, 0x7db443, 0x712db5, 0xf7614e, 0x19a3d2, 0x9fef29, 0x9376df, 0x153a24, 0x8a4533, 0x0c09c8, 0x00903e, 0x86dcc5, 0xb822eb, 0x3e6e10, 0x32f7e6, 0xb4bb1d, 0x2bc40a, 0xad88f1, 0xa11107, 0x275dfc, 0xdced5b, 0x5aa1a0, 0x563856, 0xd074ad, 0x4f0bba, 0xc94741, 0xc5deb7, 0x43924c, 0x7d6c62, 0xfb2099, 0xf7b96f, 0x71f594, 0xee8a83, 0x68c678, 0x645f8e, 0xe21375, 0x15723b, 0x933ec0, 0x9fa736, 0x19ebcd, 0x8694da, 0x00d821, 0x0c41d7, 0x8a0d2c, 0xb4f302, 0x32bff9, 0x3e260f, 0xb86af4, 0x2715e3, 0xa15918, 0xadc0ee, 0x2b8c15, 0xd03cb2, 0x567049, 0x5ae9bf, 0xdca544, 0x43da53, 0xc596a8, 0xc90f5e, 0x4f43a5, 0x71bd8b, 0xf7f170, 0xfb6886, 0x7d247d, 0xe25b6a, 0x641791, 0x688e67, 0xeec29c, 0x3347a4, 0xb50b5f, 0xb992a9, 0x3fde52, 0xa0a145, 0x26edbe, 0x2a7448, 0xac38b3, 0x92c69d, 0x148a66, 0x181390, 0x9e5f6b, 0x01207c, 0x876c87, 0x8bf571, 0x0db98a, 0xf6092d, 0x7045d6, 0x7cdc20, 0xfa90db, 0x65efcc, 0xe3a337, 0xef3ac1, 0x69763a, 0x578814, 0xd1c4ef, 0xdd5d19, 0x5b11e2, 0xc46ef5, 0x42220e, 0x4ebbf8, 0xc8f703, 0x3f964d, 0xb9dab6, 0xb54340, 0x330fbb, 0xac70ac, 0x2a3c57, 0x26a5a1, 0xa0e95a, 0x9e1774, 0x185b8f, 0x14c279, 0x928e82, 0x0df195, 0x8bbd6e, 0x872498, 0x016863, 0xfad8c4, 0x7c943f, 0x700dc9, 0xf64132, 0x693e25, 0xef72de, 0xe3eb28, 0x65a7d3, 0x5b59fd, 0xdd1506, 0xd18cf0, 0x57c00b, 0xc8bf1c, 0x4ef3e7, 0x426a11, 0xc426ea, 0x2ae476, 0xaca88d, 0xa0317b, 0x267d80, 0xb90297, 0x3f4e6c, 0x33d79a, 0xb59b61, 0x8b654f, 0x0d29b4, 0x01b042, 0x87fcb9, 0x1883ae, 0x9ecf55, 0x9256a3, 0x141a58, 0xefaaff, 0x69e604, 0x657ff2, 0xe33309, 0x7c4c1e, 0xfa00e5, 0xf69913, 0x70d5e8, 0x4e2bc6, 0xc8673d, 0xc4fecb, 0x42b230, 0xddcd27, 0x5b81dc, 0x57182a, 0xd154d1, 0x26359f, 0xa07964, 0xace092, 0x2aac69, 0xb5d37e, 0x339f85, 0x3f0673, 0xb94a88, 0x87b4a6, 0x01f85d, 0x0d61ab, 0x8b2d50, 0x145247, 0x921ebc, 0x9e874a, 0x18cbb1, 0xe37b16, 0x6537ed, 0x69ae1b, 0xefe2e0, 0x709df7, 0xf6d10c, 0xfa48fa, 0x7c0401, 0x42fa2f, 0xc4b6d4, 0xc82f22, 0x4e63d9, 0xd11cce, 0x575035, 0x5bc9c3, 0xdd8538];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('crc-24', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = previous != null ? ~~previous : 0xb704ce;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = (TABLE[((crc >> 16) ^ byte) & 0xff] ^ (crc << 8)) & 0xffffff;
  }
  return crc;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc32.js

Statements: 46.67% (7 / 15)      Branches: 16.67% (1 / 6)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('crc-32', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = previous === 0 ? 0 : ~~previous ^ -1;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
  }
  return crc ^ -1;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8.js

Statements: 46.67% (7 / 15)      Branches: 25% (1 / 4)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('crc-8', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = ~~previous;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
  }
  return crc;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/crc8_1wire.js

Statements: 46.67% (7 / 15)      Branches: 25% (1 / 4)      Functions: 0% (0 / 1)      Lines: 46.67% (7 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  1   1   1   1   1 1     1                          
// Generated by CoffeeScript 1.7.1
var Buffer, TABLE, create;
 
Buffer = require('buffer').Buffer;
 
create = require('./create');
 
TABLE = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35];
 
Eif (typeof Int32Array !== 'undefined') {
  TABLE = new Int32Array(TABLE);
}
 
module.exports = create('dallas-1-wire', function(buf, previous) {
  var byte, crc, _i, _len;
  if (!Buffer.isBuffer(buf)) {
    buf = Buffer(buf);
  }
  crc = ~~previous;
  for (_i = 0, _len = buf.length; _i < _len; _i++) {
    byte = buf[_i];
    crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
  }
  return crc;
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/create.js

Statements: 87.5% (7 / 8)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 87.5% (7 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13  1 8 8     8 8 8 8      
// Generated by CoffeeScript 1.7.1
module.exports = function(model, calc) {
  var fn;
  fn = function(buf, previous) {
    return calc(buf, previous) >>> 0;
  };
  fn.signed = calc;
  fn.unsigned = fn;
  fn.model = model;
  return fn;
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/etag/node_modules/crc/lib/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13  1                      
// Generated by CoffeeScript 1.7.1
module.exports = {
  crc1: require('./crc1'),
  crc8: require('./crc8'),
  crc81wire: require('./crc8_1wire'),
  crc16: require('./crc16'),
  crc16ccitt: require('./crc16_ccitt'),
  crc16modbus: require('./crc16_modbus'),
  crc24: require('./crc24'),
  crc32: require('./crc32')
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/finalhandler/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/finalhandler/

Statements: 37.29% (22 / 59)      Branches: 19.51% (8 / 41)      Functions: 33.33% (2 / 6)      Lines: 37.29% (22 / 59)      Ignored: 11 statements, 2 functions, 7 branches     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/finalhandler/
File Statements Branches Functions Lines
index.js 37.29% (22 / 59) 19.51% (8 / 41) 33.33% (2 / 6) 37.29% (22 / 59)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/finalhandler/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/finalhandler/index.js

Statements: 37.29% (22 / 59)      Branches: 19.51% (8 / 41)      Functions: 33.33% (2 / 6)      Lines: 37.29% (22 / 59)      Ignored: 11 statements, 2 functions, 7 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173                    1 1 1 1             1   1 1           1                       1                                                                                                                                       1 1                                                                             1 1   1 1       1 1   1 1   1 1       1        
/*!
 * finalhandler
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 */
 
var debug = require('debug')('finalhandler')
var escapeHtml = require('escape-html')
var http = require('http')
var onFinished = require('on-finished')
 
/**
 * Variables.
 */
 
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
  ? setImmediate
  : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
var isFinished = onFinished.isFinished
 
/**
 * Module exports.
 */
 
module.exports = finalhandler
 
/**
 * Final handler:
 *
 * @param {Request} req
 * @param {Response} res
 * @param {Object} [options]
 * @return {Function}
 * @api public
 */
 
function finalhandler(req, res, options) {
  options = options || {}
 
  // get environment
  var env = options.env || process.env.NODE_ENV || 'development'
 
  // get error callback
  var onerror = options.onerror
 
  return function (err) {
    var msg
 
    // ignore 404 on in-flight response
    if (!err && res._header) {
      debug('cannot 404 after headers sent')
      return
    }
 
    // unhandled error
    if (err) {
      // default status code to 500
      if (!res.statusCode || res.statusCode < 400) {
        res.statusCode = 500
      }
 
      // respect err.status
      if (err.status) {
        res.statusCode = err.status
      }
 
      // production gets a basic error message
      var msg = env === 'production'
        ? http.STATUS_CODES[res.statusCode]
        : err.stack || err.toString()
      msg = escapeHtml(msg)
        .replace(/\n/g, '<br>')
        .replace(/  /g, ' &nbsp;') + '\n'
    } else {
      res.statusCode = 404
      msg = 'Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl || req.url) + '\n'
    }
 
    debug('default %s', res.statusCode)
 
    // schedule onerror callback
    if (err && onerror) {
      defer(onerror, err, req, res)
    }
 
    // cannot actually respond
    if (res._header) {
      return req.socket.destroy()
    }
 
    send(req, res, res.statusCode, msg)
  }
}
 
/**
 * Send response.
 *
 * @param {IncomingMessage} req
 * @param {OutgoingMessage} res
 * @param {number} status
 * @param {string} body
 * @api private
 */
 
function send(req, res, status, body) {
  function write() {
    res.statusCode = status
 
    // security header for content sniffing
    res.setHeader('X-Content-Type-Options', 'nosniff')
 
    // standard headers
    res.setHeader('Content-Type', 'text/html; charset=utf-8')
    res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
 
    if (req.method === 'HEAD') {
      res.end()
      return
    }
 
    res.end(body, 'utf8')
  }
 
  if (isFinished(req)) {
    write()
    return
  }
 
  // unpipe everything from the request
  unpipe(req)
 
  // flush the request
  onFinished(req, write)
  req.resume()
}
 
/**
 * Unpipe everything from a stream.
 *
 * @param {Object} stream
 * @api private
 */
 
/* istanbul ignore next: implementation differs between versions */
function unpipe(stream) {
  if (typeof stream.unpipe === 'function') {
    // new-style
    stream.unpipe()
    return
  }
 
  // Node.js 0.8 hack
  var listener
  var listeners = stream.listeners('close')
 
  for (var i = 0; i < listeners.length; i++) {
    listener = listeners[i]
 
    if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
      continue
    }
 
    // invoke the listener
    listener.call(stream)
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/fresh/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/fresh/

Statements: 9.09% (2 / 22)      Branches: 0% (0 / 18)      Functions: 0% (0 / 1)      Lines: 11.11% (2 / 18)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/fresh/
File Statements Branches Functions Lines
index.js 9.09% (2 / 22) 0% (0 / 18) 0% (0 / 1) 11.11% (2 / 18)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/fresh/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/fresh/index.js

Statements: 9.09% (2 / 22)      Branches: 0% (0 / 18)      Functions: 0% (0 / 1)      Lines: 11.11% (2 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54          1                             1                                                                  
 
/**
 * Expose `fresh()`.
 */
 
module.exports = fresh;
 
/**
 * Check freshness of `req` and `res` headers.
 *
 * When the cache is "fresh" __true__ is returned,
 * otherwise __false__ is returned to indicate that
 * the cache is now stale.
 *
 * @param {Object} req
 * @param {Object} res
 * @return {Boolean}
 * @api public
 */
 
function fresh(req, res) {
  // defaults
  var etagMatches = true;
  var notModified = true;
 
  // fields
  var modifiedSince = req['if-modified-since'];
  var noneMatch = req['if-none-match'];
  var lastModified = res['last-modified'];
  var etag = res['etag'];
  var cc = req['cache-control'];
 
  // unconditional request
  if (!modifiedSince && !noneMatch) return false;
 
  // check for no-cache cache request directive
  if (cc && cc.indexOf('no-cache') !== -1) return false;  
 
  // parse if-none-match
  if (noneMatch) noneMatch = noneMatch.split(/ *, */);
 
  // if-none-match
  if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0];
 
  // if-modified-since
  if (modifiedSince) {
    modifiedSince = new Date(modifiedSince);
    lastModified = new Date(lastModified);
    notModified = lastModified <= modifiedSince;
  }
 
  return !! (etagMatches && notModified);
}
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/media-typer/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/media-typer/

Statements: 17.05% (15 / 88)      Branches: 0% (0 / 54)      Functions: 0% (0 / 5)      Lines: 17.05% (15 / 88)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/media-typer/
File Statements Branches Functions Lines
index.js 17.05% (15 / 88) 0% (0 / 54) 0% (0 / 5) 17.05% (15 / 88)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/media-typer/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/media-typer/index.js

Statements: 17.05% (15 / 88)      Branches: 0% (0 / 54)      Functions: 0% (0 / 5)      Lines: 17.05% (15 / 88)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272                                                          1 1 1               1         1                                   1 1 1           1 1                   1                                                                                                                 1                                                                                                                             1                                       1                                             1                                                      
/*!
 * media-typer
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7
 *
 * parameter     = token "=" ( token | quoted-string )
 * token         = 1*<any CHAR except CTLs or separators>
 * separators    = "(" | ")" | "<" | ">" | "@"
 *               | "," | ";" | ":" | "\" | <">
 *               | "/" | "[" | "]" | "?" | "="
 *               | "{" | "}" | SP | HT
 * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
 * qdtext        = <any TEXT except <">>
 * quoted-pair   = "\" CHAR
 * CHAR          = <any US-ASCII character (octets 0 - 127)>
 * TEXT          = <any OCTET except CTLs, but including LWS>
 * LWS           = [CRLF] 1*( SP | HT )
 * CRLF          = CR LF
 * CR            = <US-ASCII CR, carriage return (13)>
 * LF            = <US-ASCII LF, linefeed (10)>
 * SP            = <US-ASCII SP, space (32)>
 * SHT           = <US-ASCII HT, horizontal-tab (9)>
 * CTL           = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
 * OCTET         = <any 8-bit sequence of data>
 */
var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g;
var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/
var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/
 
/**
 * RegExp to match quoted-pair in RFC 2616
 *
 * quoted-pair = "\" CHAR
 * CHAR        = <any US-ASCII character (octets 0 - 127)>
 */
var qescRegExp = /\\([\u0000-\u007f])/g;
 
/**
 * RegExp to match chars that must be quoted-pair in RFC 2616
 */
var quoteRegExp = /([\\"])/g;
 
/**
 * RegExp to match type in RFC 6838
 *
 * type-name = restricted-name
 * subtype-name = restricted-name
 * restricted-name = restricted-name-first *126restricted-name-chars
 * restricted-name-first  = ALPHA / DIGIT
 * restricted-name-chars  = ALPHA / DIGIT / "!" / "#" /
 *                          "$" / "&" / "-" / "^" / "_"
 * restricted-name-chars =/ "." ; Characters before first dot always
 *                              ; specify a facet name
 * restricted-name-chars =/ "+" ; Characters after last plus always
 *                              ; specify a structured syntax suffix
 * ALPHA =  %x41-5A / %x61-7A   ; A-Z / a-z
 * DIGIT =  %x30-39             ; 0-9
 */
var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/
var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/
var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;
 
/**
 * Module exports.
 */
 
exports.format = format
exports.parse = parse
 
/**
 * Format object to media type.
 *
 * @param {object} obj
 * @return {string}
 * @api public
 */
 
function format(obj) {
  if (!obj || typeof obj !== 'object') {
    throw new TypeError('argument obj is required')
  }
 
  var parameters = obj.parameters
  var subtype = obj.subtype
  var suffix = obj.suffix
  var type = obj.type
 
  if (!type || !typeNameRegExp.test(type)) {
    throw new TypeError('invalid type')
  }
 
  if (!subtype || !subtypeNameRegExp.test(subtype)) {
    throw new TypeError('invalid subtype')
  }
 
  // format as type/subtype
  var string = type + '/' + subtype
 
  // append +suffix
  if (suffix) {
    if (!typeNameRegExp.test(suffix)) {
      throw new TypeError('invalid suffix')
    }
 
    string += '+' + suffix
  }
 
  // append parameters
  if (parameters && typeof parameters === 'object') {
    var param
    var params = Object.keys(parameters).sort()
 
    for (var i = 0; i < params.length; i++) {
      param = params[i]
 
      if (!tokenRegExp.test(param)) {
        throw new TypeError('invalid parameter name')
      }
 
      string += '; ' + param + '=' + qstring(parameters[param])
    }
  }
 
  return string
}
 
/**
 * Parse media type to object.
 *
 * @param {string|object} string
 * @return {Object}
 * @api public
 */
 
function parse(string) {
  if (!string) {
    throw new TypeError('argument string is required')
  }
 
  // support req/res-like objects as argument
  if (typeof string === 'object') {
    string = getcontenttype(string)
  }
 
  if (typeof string !== 'string') {
    throw new TypeError('argument string is required to be a string')
  }
 
  var index = string.indexOf(';')
  var type = index !== -1
    ? string.substr(0, index)
    : string
 
  var key
  var match
  var obj = splitType(type)
  var params = {}
  var value
 
  paramRegExp.lastIndex = index
 
  while (match = paramRegExp.exec(string)) {
    if (match.index !== index) {
      throw new TypeError('invalid parameter format')
    }
 
    index += match[0].length
    key = match[1].toLowerCase()
    value = match[2]
 
    if (value[0] === '"') {
      // remove quotes and escapes
      value = value
        .substr(1, value.length - 2)
        .replace(qescRegExp, '$1')
    }
 
    params[key] = value
  }
 
  if (index !== -1 && index !== string.length) {
    throw new TypeError('invalid parameter format')
  }
 
  obj.parameters = params
 
  return obj
}
 
/**
 * Get content-type from req/res objects.
 *
 * @param {object}
 * @return {Object}
 * @api private
 */
 
function getcontenttype(obj) {
  if (typeof obj.getHeader === 'function') {
    // res-like
    return obj.getHeader('content-type')
  }
 
  if (typeof obj.headers === 'object') {
    // req-like
    return obj.headers && obj.headers['content-type']
  }
}
 
/**
 * Quote a string if necessary.
 *
 * @param {string} val
 * @return {string}
 * @api private
 */
 
function qstring(val) {
  var str = String(val)
 
  // no need to quote tokens
  if (tokenRegExp.test(str)) {
    return str
  }
 
  if (str.length > 0 && !textRegExp.test(str)) {
    throw new TypeError('invalid parameter value')
  }
 
  return '"' + str.replace(quoteRegExp, '\\$1') + '"'
}
 
/**
 * Simply "type/subtype+siffx" into parts.
 *
 * @param {string} string
 * @return {Object}
 * @api private
 */
 
function splitType(string) {
  var match = typeRegExp.exec(string.toLowerCase())
 
  if (!match) {
    throw new TypeError('invalid media type')
  }
 
  var type = match[1]
  var subtype = match[2]
  var suffix
 
  // suffix after last +
  var index = subtype.lastIndexOf('+')
  if (index !== -1) {
    suffix = subtype.substr(index + 1)
    subtype = subtype.substr(0, index)
  }
 
  var obj = {
    type: type,
    subtype: subtype,
    suffix: suffix
  }
 
  return obj
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/merge-descriptors/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/merge-descriptors/

Statements: 20% (1 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 20% (1 / 5)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/merge-descriptors/
File Statements Branches Functions Lines
index.js 20% (1 / 5) 100% (0 / 0) 0% (0 / 2) 20% (1 / 5)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/merge-descriptors/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/merge-descriptors/index.js

Statements: 20% (1 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 20% (1 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 91                
module.exports = function (dest, src) {
  Object.getOwnPropertyNames(src).forEach(function (name) {
    var descriptor = Object.getOwnPropertyDescriptor(src, name)
    Object.defineProperty(dest, name, descriptor)
  })
 
  return dest
}
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/methods/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/methods/

Statements: 80% (4 / 5)      Branches: 50% (1 / 2)      Functions: 100% (1 / 1)      Lines: 80% (4 / 5)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/methods/
File Statements Branches Functions Lines
index.js 80% (4 / 5) 50% (1 / 2) 100% (1 / 1) 80% (4 / 5)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/methods/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/methods/index.js

Statements: 80% (4 / 5)      Branches: 50% (1 / 2)      Functions: 100% (1 / 1)      Lines: 80% (4 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43  1   1   1 33                                                                        
 
var http = require('http');
 
Eif (http.METHODS) {
 
  module.exports = http.METHODS.map(function(method){
    return method.toLowerCase();
  });
 
} else {
 
  module.exports = [
    'get',
    'post',
    'put',
    'head',
    'delete',
    'options',
    'trace',
    'copy',
    'lock',
    'mkcol',
    'move',
    'purge',
    'propfind',
    'proppatch',
    'unlock',
    'report',
    'mkactivity',
    'checkout',
    'merge',
    'm-search',
    'notify',
    'subscribe',
    'unsubscribe',
    'patch',
    'search',
    'connect'
  ];
 
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/

Statements: 21.21% (14 / 66)      Branches: 6.25% (2 / 32)      Functions: 9.09% (1 / 11)      Lines: 22.95% (14 / 61)      Ignored: 1 statement, 1 function, 1 branch     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/
File Statements Branches Functions Lines
index.js 21.21% (14 / 66) 6.25% (2 / 32) 9.09% (1 / 11) 22.95% (14 / 61)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/index.js

Statements: 21.21% (14 / 66)      Branches: 6.25% (2 / 32)      Functions: 9.09% (1 / 11)      Lines: 22.95% (14 / 61)      Ignored: 1 statement, 1 function, 1 branch     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193                      1 1           1             1   1                       1                                       1                                                 1         1                     1                                                                   1                                       1 1                                                 1                        
/*!
 * on-finished
 * Copyright(c) 2013 Jonathan Ong
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = onFinished;
module.exports.isFinished = isFinished;
 
/**
* Module dependencies.
*/
 
var first = require('ee-first')
 
/**
* Variables.
*/
 
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
  ? setImmediate
  : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
 
/**
 * Invoke callback when the response has finished, useful for
 * cleaning up resources afterwards.
 *
 * @param {object} msg
 * @param {function} listener
 * @return {object}
 * @api public
 */
 
function onFinished(msg, listener) {
  if (isFinished(msg) !== false) {
    defer(listener)
    return msg
  }
 
  // attach the listener to the message
  attachListener(msg, listener)
 
  return msg
}
 
/**
 * Determine if message is already finished.
 *
 * @param {object} msg
 * @return {boolean}
 * @api public
 */
 
function isFinished(msg) {
  var socket = msg.socket
 
  if (typeof msg.finished === 'boolean') {
    // OutgoingMessage
    return Boolean(msg.finished || (socket && !socket.writable))
  }
 
  if (typeof msg.complete === 'boolean') {
    // IncomingMessage
    return Boolean(!socket || msg.complete || !socket.readable)
  }
 
  // don't know
  return undefined
}
 
/**
 * Attach a finished listener to the message.
 *
 * @param {object} msg
 * @param {function} callback
 * @private
 */
 
function attachFinishedListener(msg, callback) {
  var eeMsg
  var eeSocket
  var finished = false
 
  function onFinish(error) {
    eeMsg.cancel()
    eeSocket.cancel()
 
    finished = true
    callback(error)
  }
 
  // finished on first message event
  eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish)
 
  function onSocket(socket) {
    // remove listener
    msg.removeListener('socket', onSocket)
 
    if (finished) return
    if (eeMsg !== eeSocket) return
 
    // finished on first socket event
    eeSocket = first([[socket, 'error', 'close']], onFinish)
  }
 
  if (msg.socket) {
    // socket already assigned
    onSocket(msg.socket)
    return
  }
 
  // wait for socket to be assigned
  msg.on('socket', onSocket)
 
  if (msg.socket === undefined) {
    // node.js 0.8 patch
    patchAssignSocket(msg, onSocket)
  }
}
 
/**
 * Attach the listener to the message.
 *
 * @param {object} msg
 * @return {function}
 * @api private
 */
 
function attachListener(msg, listener) {
  var attached = msg.__onFinished
 
  // create a private single listener with queue
  if (!attached || !attached.queue) {
    attached = msg.__onFinished = createListener(msg)
    attachFinishedListener(msg, attached)
  }
 
  attached.queue.push(listener)
}
 
/**
 * Create listener on message.
 *
 * @param {object} msg
 * @return {function}
 * @api private
 */
 
function createListener(msg) {
  function listener(err) {
    if (msg.__onFinished === listener) msg.__onFinished = null
    if (!listener.queue) return
 
    var queue = listener.queue
    listener.queue = null
 
    for (var i = 0; i < queue.length; i++) {
      queue[i](err)
    }
  }
 
  listener.queue = []
 
  return listener
}
 
/**
 * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
 *
 * @param {ServerResponse} res
 * @param {function} callback
 * @private
 */
 
function patchAssignSocket(res, callback) {
  var assignSocket = res.assignSocket
 
  if (typeof assignSocket !== 'function') return
 
  // res.on('socket', callback) is broken in 0.8
  res.assignSocket = function _assignSocket(socket) {
    assignSocket.call(this, socket)
    callback(socket)
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/node_modules/ee-first/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/node_modules/ee-first/

Statements: 14.71% (5 / 34)      Branches: 0% (0 / 8)      Functions: 0% (0 / 6)      Lines: 14.71% (5 / 34)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/node_modules/ee-first/
File Statements Branches Functions Lines
index.js 14.71% (5 / 34) 0% (0 / 8) 0% (0 / 6) 14.71% (5 / 34)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js

Statements: 14.71% (5 / 34)      Branches: 0% (0 / 8)      Functions: 0% (0 / 6)      Lines: 14.71% (5 / 34)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70  1                                                         1         1               1                 1                                  
 
module.exports = function first(stuff, done) {
  if (!Array.isArray(stuff))
    throw new TypeError('arg must be an array of [ee, events...] arrays')
 
  var cleanups = []
 
  for (var i = 0; i < stuff.length; i++) {
    var arr = stuff[i]
 
    if (!Array.isArray(arr) || arr.length < 2)
      throw new TypeError('each array member must be [ee, events...]')
 
    var ee = arr[0]
 
    for (var j = 1; j < arr.length; j++) {
      var event = arr[j]
      var fn = listener(event, callback)
 
      // listen to the event
      ee.on(event, fn)
      // push this listener to the list of cleanups
      cleanups.push({
        ee: ee,
        event: event,
        fn: fn,
      })
    }
  }
 
  function callback() {
    cleanup()
    done.apply(null, arguments)
  }
 
  function cleanup() {
    var x
    for (var i = 0; i < cleanups.length; i++) {
      x = cleanups[i]
      x.ee.removeListener(x.event, x.fn)
    }
  }
 
  function thunk(fn) {
    done = fn
  }
 
  thunk.cancel = cleanup
 
  return thunk
}
 
function listener(event, done) {
  return function onevent(arg1) {
    var args = new Array(arguments.length)
    var ee = this
    var err = event === 'error'
      ? arg1
      : null
 
    // copy args to prevent arguments escaping scope
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i]
    }
 
    done(err, ee, event, args)
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/parseurl/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/parseurl/

Statements: 24.39% (10 / 41)      Branches: 0% (0 / 23)      Functions: 0% (0 / 4)      Lines: 24.39% (10 / 41)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/parseurl/
File Statements Branches Functions Lines
index.js 24.39% (10 / 41) 0% (0 / 23) 0% (0 / 4) 24.39% (10 / 41)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/parseurl/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/parseurl/index.js

Statements: 24.39% (10 / 41)      Branches: 0% (0 / 23)      Functions: 0% (0 / 4)      Lines: 24.39% (10 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138                      1 1 1             1           1 1                   1                                                           1                                                           1                                                                 1              
/*!
 * parseurl
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 */
 
var url = require('url')
var parse = url.parse
var Url = url.Url
 
/**
 * Pattern for a simple path case.
 * See: https://github.com/joyent/node/pull/7878
 */
 
var simplePathRegExp = /^(\/\/?(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/
 
/**
 * Exports.
 */
 
module.exports = parseurl
module.exports.original = originalurl
 
/**
 * Parse the `req` url with memoization.
 *
 * @param {ServerRequest} req
 * @return {Object}
 * @api public
 */
 
function parseurl(req) {
  var url = req.url
 
  if (url === undefined) {
    // URL is undefined
    return undefined
  }
 
  var parsed = req._parsedUrl
 
  if (fresh(url, parsed)) {
    // Return cached URL parse
    return parsed
  }
 
  // Parse the URL
  parsed = fastparse(url)
  parsed._raw = url
 
  return req._parsedUrl = parsed
};
 
/**
 * Parse the `req` original url with fallback and memoization.
 *
 * @param {ServerRequest} req
 * @return {Object}
 * @api public
 */
 
function originalurl(req) {
  var url = req.originalUrl
 
  if (typeof url !== 'string') {
    // Fallback
    return parseurl(req)
  }
 
  var parsed = req._parsedOriginalUrl
 
  if (fresh(url, parsed)) {
    // Return cached URL parse
    return parsed
  }
 
  // Parse the URL
  parsed = fastparse(url)
  parsed._raw = url
 
  return req._parsedOriginalUrl = parsed
};
 
/**
 * Parse the `str` url with fast-path short-cut.
 *
 * @param {string} str
 * @return {Object}
 * @api private
 */
 
function fastparse(str) {
  // Try fast path regexp
  // See: https://github.com/joyent/node/pull/7878
  var simplePath = typeof str === 'string' && simplePathRegExp.exec(str)
 
  // Construct simple URL
  if (simplePath) {
    var pathname = simplePath[1]
    var search = simplePath[2] || null
    var url = Url !== undefined
      ? new Url()
      : {}
    url.path = str
    url.href = str
    url.pathname = pathname
    url.search = search
    url.query = search && search.substr(1)
 
    return url
  }
 
  return parse(str)
}
 
/**
 * Determine if parsed is still fresh for url.
 *
 * @param {string} url
 * @param {object} parsedUrl
 * @return {boolean}
 * @api private
 */
 
function fresh(url, parsedUrl) {
  return typeof parsedUrl === 'object'
    && parsedUrl !== null
    && (Url === undefined || parsedUrl instanceof Url)
    && parsedUrl._raw === url
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/path-to-regexp/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/path-to-regexp/

Statements: 9.09% (2 / 22)      Branches: 0% (0 / 32)      Functions: 0% (0 / 3)      Lines: 9.09% (2 / 22)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/path-to-regexp/
File Statements Branches Functions Lines
index.js 9.09% (2 / 22) 0% (0 / 32) 0% (0 / 3) 9.09% (2 / 22)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/path-to-regexp/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/path-to-regexp/index.js

Statements: 9.09% (2 / 22)      Branches: 0% (0 / 32)      Functions: 0% (0 / 3)      Lines: 9.09% (2 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72        1                                   1                                                                                                  
/**
 * Expose `pathtoRegexp`.
 */
 
module.exports = pathtoRegexp;
 
/**
 * Normalize the given path string,
 * returning a regular expression.
 *
 * An empty array should be passed,
 * which will contain the placeholder
 * key names. For example "/user/:id" will
 * then contain ["id"].
 *
 * @param  {String|RegExp|Array} path
 * @param  {Array} keys
 * @param  {Object} options
 * @return {RegExp}
 * @api private
 */
 
function pathtoRegexp(path, keys, options) {
  options = options || {};
  var strict = options.strict;
  var end = options.end !== false;
  var flags = options.sensitive ? '' : 'i';
  keys = keys || [];
 
  if (path instanceof RegExp) {
    return path;
  }
 
  if (Array.isArray(path)) {
    // Map array parts into regexps and return their source. We also pass
    // the same keys and options instance into every generation to get
    // consistent matching groups before we join the sources together.
    path = path.map(function (value) {
      return pathtoRegexp(value, keys, options).source;
    });
 
    return new RegExp('(?:' + path.join('|') + ')', flags);
  }
 
  path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?'))
    .replace(/\/\(/g, '/(?:')
    .replace(/([\/\.])/g, '\\$1')
    .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional) {
      slash = slash || '';
      format = format || '';
      capture = capture || '([^\\/' + format + ']+?)';
      optional = optional || '';
 
      keys.push({ name: key, optional: !!optional });
 
      return ''
        + (optional ? '' : slash)
        + '(?:'
        + format + (optional ? slash : '') + capture
        + (star ? '((?:[\\/' + format + '].+?)?)' : '')
        + ')'
        + optional;
    })
    .replace(/\*/g, '(.*)');
 
  // If the path is non-ending, match until the end or a slash.
  path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)'));
 
  return new RegExp(path, flags);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/

Statements: 14.18% (19 / 134)      Branches: 0% (0 / 72)      Functions: 0% (0 / 12)      Lines: 14.62% (19 / 130)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/
File Statements Branches Functions Lines
index.js 14.18% (19 / 134) 0% (0 / 72) 0% (0 / 12) 14.62% (19 / 130)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/index.js

Statements: 14.18% (19 / 134)      Branches: 0% (0 / 72)      Functions: 0% (0 / 12)      Lines: 14.62% (19 / 130)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347                    1 1 1           1 1           1 1 1           1                             1                                                         1                                                                       1                                 1                                 1                                                                                                               1                                                                                             1                                         1                     1                                                                                       1                                        
/*!
 * proxy-addr
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = proxyaddr;
module.exports.all = alladdrs;
module.exports.compile = compile;
 
/**
 * Module dependencies.
 */
 
var forwarded = require('forwarded');
var ipaddr = require('ipaddr.js');
 
/**
 * Variables.
 */
 
var digitre = /^[0-9]+$/;
var isip = ipaddr.isValid;
var parseip = ipaddr.parse;
 
/**
 * Pre-defined IP ranges.
 */
 
var ipranges = {
  linklocal: ['169.254.0.0/16', 'fe80::/10'],
  loopback: ['127.0.0.1/8', '::1/128'],
  uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7']
};
 
/**
 * Get all addresses in the request, optionally stopping
 * at the first untrusted.
 *
 * @param {Object} request
 * @param {Function|Array|String} [trust]
 * @api public
 */
 
function alladdrs(req, trust) {
  // get addresses
  var addrs = forwarded(req);
 
  if (!trust) {
    // Return all addresses
    return addrs;
  }
 
  if (typeof trust !== 'function') {
    trust = compile(trust);
  }
 
  for (var i = 0; i < addrs.length - 1; i++) {
    if (trust(addrs[i], i)) continue;
 
    addrs.length = i + 1;
  }
 
  return addrs;
}
 
/**
 * Compile argument into trust function.
 *
 * @param {Array|String} val
 * @api private
 */
 
function compile(val) {
  if (!val) {
    throw new TypeError('argument is required');
  }
 
  var trust = typeof val === 'string'
    ? [val]
    : val;
 
  if (!Array.isArray(trust)) {
    throw new TypeError('unsupported trust argument');
  }
 
  for (var i = 0; i < trust.length; i++) {
    val = trust[i];
 
    if (!ipranges.hasOwnProperty(val)) {
      continue;
    }
 
    // Splice in pre-defined range
    val = ipranges[val];
    trust.splice.apply(trust, [i, 1].concat(val));
    i += val.length - 1;
  }
 
  return compileTrust(compileRangeSubnets(trust));
}
 
/**
 * Compile `arr` elements into range subnets.
 *
 * @param {Array} arr
 * @api private
 */
 
function compileRangeSubnets(arr) {
  var rangeSubnets = new Array(arr.length);
 
  for (var i = 0; i < arr.length; i++) {
    rangeSubnets[i] = parseipNotation(arr[i]);
  }
 
  return rangeSubnets;
}
 
/**
 * Compile range subnet array into trust function.
 *
 * @param {Array} rangeSubnets
 * @api private
 */
 
function compileTrust(rangeSubnets) {
  // Return optimized function based on length
  var len = rangeSubnets.length;
  return len === 0
    ? trustNone
    : len === 1
    ? trustSingle(rangeSubnets[0])
    : trustMulti(rangeSubnets);
}
 
/**
 * Parse IP notation string into range subnet.
 *
 * @param {String} note
 * @api private
 */
 
function parseipNotation(note) {
  var ip;
  var kind;
  var max;
  var pos = note.lastIndexOf('/');
  var range;
 
  ip = pos !== -1
    ? note.substring(0, pos)
    : note;
 
  if (!isip(ip)) {
    throw new TypeError('invalid IP address: ' + ip);
  }
 
  ip = parseip(ip);
 
  kind = ip.kind();
  max = kind === 'ipv6'
    ? 128
    : 32;
 
  range = pos !== -1
    ? note.substring(pos + 1, note.length)
    : max;
 
  if (typeof range !== 'number') {
    range = digitre.test(range)
      ? parseInt(range, 10)
      : isip(range)
      ? parseNetmask(range)
      : 0;
  }
 
  if (ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {
    // Store as IPv4
    ip = ip.toIPv4Address();
    range = range <= max
      ? range - 96
      : range;
  }
 
  if (range <= 0 || range > max) {
    throw new TypeError('invalid range on address: ' + note);
  }
 
  return [ip, range];
}
 
/**
 * Parse netmask string into CIDR range.
 *
 * @param {String} note
 * @api private
 */
 
function parseNetmask(netmask) {
  var ip = parseip(netmask);
  var parts;
  var size;
 
  switch (ip.kind()) {
    case 'ipv4':
      parts = ip.octets;
      size = 8;
      break;
    case 'ipv6':
      parts = ip.parts;
      size = 16;
      break;
  }
 
  var max = Math.pow(2, size) - 1;
  var part;
  var range = 0;
 
  for (var i = 0; i < parts.length; i++) {
    part = parts[i] & max;
 
    if (part === max) {
      range += size;
      continue;
    }
 
    while (part) {
      part = (part << 1) & max;
      range += 1;
    }
 
    break;
  }
 
  return range;
}
 
/**
 * Determine address of proxied request.
 *
 * @param {Object} request
 * @param {Function|Array|String} trust
 * @api public
 */
 
function proxyaddr(req, trust) {
  if (!req) {
    throw new TypeError('req argument is required');
  }
 
  if (!trust) {
    throw new TypeError('trust argument is required');
  }
 
  var addrs = alladdrs(req, trust);
  var addr = addrs[addrs.length - 1];
 
  return addr;
}
 
/**
 * Static trust function to trust nothing.
 *
 * @api private
 */
 
function trustNone() {
  return false;
}
 
/**
 * Compile trust function for multiple subnets.
 *
 * @param {Array} subnets
 * @api private
 */
 
function trustMulti(subnets) {
  return function trust(addr) {
    if (!isip(addr)) return false;
 
    var ip = parseip(addr);
    var ipv4;
    var kind = ip.kind();
    var subnet;
    var subnetip;
    var subnetkind;
    var subnetrange;
    var trusted;
 
    for (var i = 0; i < subnets.length; i++) {
      subnet = subnets[i];
      subnetip = subnet[0];
      subnetkind = subnetip.kind();
      subnetrange = subnet[1];
      trusted = ip;
 
      if (kind !== subnetkind) {
        if (kind !== 'ipv6' || subnetkind !== 'ipv4' || !ip.isIPv4MappedAddress()) {
          continue;
        }
 
        // Store addr as IPv4
        ipv4 = ipv4 || ip.toIPv4Address();
        trusted = ipv4;
      }
 
      if (trusted.match(subnetip, subnetrange)) return true;
    }
 
    return false;
  };
}
 
/**
 * Compile trust function for single subnet.
 *
 * @param {Object} subnet
 * @api private
 */
 
function trustSingle(subnet) {
  var subnetip = subnet[0];
  var subnetkind = subnetip.kind();
  var subnetisipv4 = subnetkind === 'ipv4';
  var subnetrange = subnet[1];
 
  return function trust(addr) {
    if (!isip(addr)) return false;
 
    var ip = parseip(addr);
    var kind = ip.kind();
 
    return kind === subnetkind
      ? ip.match(subnetip, subnetrange)
      : subnetisipv4 && kind === 'ipv6' && ip.isIPv4MappedAddress()
      ? ip.toIPv4Address().match(subnetip, subnetrange)
      : false;
  };
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/

Statements: 25% (2 / 8)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 25% (2 / 8)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/
File Statements Branches Functions Lines
index.js 25% (2 / 8) 0% (0 / 4) 0% (0 / 1) 25% (2 / 8)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/forwarded/index.js

Statements: 25% (2 / 8)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 25% (2 / 8)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37                    1                 1                                  
/*!
 * forwarded
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = forwarded
 
/**
 * Get all addresses in the request, using the `X-Forwarded-For` header.
 *
 * @param {Object} req
 * @api public
 */
 
function forwarded(req) {
  if (!req) {
    throw new TypeError('argument req is required')
  }
 
  // simple header parsing
  var proxyAddrs = (req.headers['x-forwarded-for'] || '')
    .split(/ *, */)
    .filter(Boolean)
    .reverse()
  var socketAddr = req.connection.remoteAddress
  var addrs = [socketAddr].concat(proxyAddrs)
 
  // return all addresses
  return addrs
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/

Statements: 21.59% (57 / 264)      Branches: 12.63% (12 / 95)      Functions: 12.82% (5 / 39)      Lines: 21.59% (57 / 264)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/
File Statements Branches Functions Lines
ipaddr.js 21.59% (57 / 264) 12.63% (12 / 95) 12.82% (5 / 39) 21.59% (57 / 264)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js

Statements: 21.59% (57 / 264)      Branches: 12.63% (12 / 95)      Functions: 12.82% (5 / 39)      Lines: 21.59% (57 / 264)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 4411 1   1   1   1 1         1                                       1                                       1 1 14 14     14 56 56       14     1       1       1       1                     1                   1       1       1       1   1         1                                                                           1 1 11 11     11 88 88       11     1       1                                                                                                         1                       1                           1                     1                           1       1       1                 1       1   1         1                                                                                     1                             1       1                     1                 1               1       1                   1                             1                        
(function() {
  var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root;
 
  ipaddr = {};
 
  root = this;
 
  Eif ((typeof module !== "undefined" && module !== null) && module.exports) {
    module.exports = ipaddr;
  } else {
    root['ipaddr'] = ipaddr;
  }
 
  matchCIDR = function(first, second, partSize, cidrBits) {
    var part, shift;
    if (first.length !== second.length) {
      throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
    }
    part = 0;
    while (cidrBits > 0) {
      shift = partSize - cidrBits;
      if (shift < 0) {
        shift = 0;
      }
      if (first[part] >> shift !== second[part] >> shift) {
        return false;
      }
      cidrBits -= partSize;
      part += 1;
    }
    return true;
  };
 
  ipaddr.subnetMatch = function(address, rangeList, defaultName) {
    var rangeName, rangeSubnets, subnet, _i, _len;
    if (defaultName == null) {
      defaultName = 'unicast';
    }
    for (rangeName in rangeList) {
      rangeSubnets = rangeList[rangeName];
      if (toString.call(rangeSubnets[0]) !== '[object Array]') {
        rangeSubnets = [rangeSubnets];
      }
      for (_i = 0, _len = rangeSubnets.length; _i < _len; _i++) {
        subnet = rangeSubnets[_i];
        if (address.match.apply(address, subnet)) {
          return rangeName;
        }
      }
    }
    return defaultName;
  };
 
  ipaddr.IPv4 = (function() {
    function IPv4(octets) {
      var octet, _i, _len;
      Iif (octets.length !== 4) {
        throw new Error("ipaddr: ipv4 octet count should be 4");
      }
      for (_i = 0, _len = octets.length; _i < _len; _i++) {
        octet = octets[_i];
        Iif (!((0 <= octet && octet <= 255))) {
          throw new Error("ipaddr: ipv4 octet is a byte");
        }
      }
      this.octets = octets;
    }
 
    IPv4.prototype.kind = function() {
      return 'ipv4';
    };
 
    IPv4.prototype.toString = function() {
      return this.octets.join(".");
    };
 
    IPv4.prototype.toByteArray = function() {
      return this.octets.slice(0);
    };
 
    IPv4.prototype.match = function(other, cidrRange) {
      var _ref;
      if (cidrRange === void 0) {
        _ref = other, other = _ref[0], cidrRange = _ref[1];
      }
      if (other.kind() !== 'ipv4') {
        throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
      }
      return matchCIDR(this.octets, other.octets, 8, cidrRange);
    };
 
    IPv4.prototype.SpecialRanges = {
      unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
      broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
      multicast: [[new IPv4([224, 0, 0, 0]), 4]],
      linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
      loopback: [[new IPv4([127, 0, 0, 0]), 8]],
      "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
      reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
    };
 
    IPv4.prototype.range = function() {
      return ipaddr.subnetMatch(this, this.SpecialRanges);
    };
 
    IPv4.prototype.toIPv4MappedAddress = function() {
      return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
    };
 
    return IPv4;
 
  })();
 
  ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
 
  ipv4Regexes = {
    fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
    longValue: new RegExp("^" + ipv4Part + "$", 'i')
  };
 
  ipaddr.IPv4.parser = function(string) {
    var match, parseIntAuto, part, shift, value;
    parseIntAuto = function(string) {
      if (string[0] === "0" && string[1] !== "x") {
        return parseInt(string, 8);
      } else {
        return parseInt(string);
      }
    };
    if (match = string.match(ipv4Regexes.fourOctet)) {
      return (function() {
        var _i, _len, _ref, _results;
        _ref = match.slice(1, 6);
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          part = _ref[_i];
          _results.push(parseIntAuto(part));
        }
        return _results;
      })();
    } else if (match = string.match(ipv4Regexes.longValue)) {
      value = parseIntAuto(match[1]);
      if (value > 0xffffffff || value < 0) {
        throw new Error("ipaddr: address outside defined range");
      }
      return ((function() {
        var _i, _results;
        _results = [];
        for (shift = _i = 0; _i <= 24; shift = _i += 8) {
          _results.push((value >> shift) & 0xff);
        }
        return _results;
      })()).reverse();
    } else {
      return null;
    }
  };
 
  ipaddr.IPv6 = (function() {
    function IPv6(parts) {
      var part, _i, _len;
      Iif (parts.length !== 8) {
        throw new Error("ipaddr: ipv6 part count should be 8");
      }
      for (_i = 0, _len = parts.length; _i < _len; _i++) {
        part = parts[_i];
        Iif (!((0 <= part && part <= 0xffff))) {
          throw new Error("ipaddr: ipv6 part should fit to two octets");
        }
      }
      this.parts = parts;
    }
 
    IPv6.prototype.kind = function() {
      return 'ipv6';
    };
 
    IPv6.prototype.toString = function() {
      var compactStringParts, part, pushPart, state, stringParts, _i, _len;
      stringParts = (function() {
        var _i, _len, _ref, _results;
        _ref = this.parts;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          part = _ref[_i];
          _results.push(part.toString(16));
        }
        return _results;
      }).call(this);
      compactStringParts = [];
      pushPart = function(part) {
        return compactStringParts.push(part);
      };
      state = 0;
      for (_i = 0, _len = stringParts.length; _i < _len; _i++) {
        part = stringParts[_i];
        switch (state) {
          case 0:
            if (part === '0') {
              pushPart('');
            } else {
              pushPart(part);
            }
            state = 1;
            break;
          case 1:
            if (part === '0') {
              state = 2;
            } else {
              pushPart(part);
            }
            break;
          case 2:
            if (part !== '0') {
              pushPart('');
              pushPart(part);
              state = 3;
            }
            break;
          case 3:
            pushPart(part);
        }
      }
      if (state === 2) {
        pushPart('');
        pushPart('');
      }
      return compactStringParts.join(":");
    };
 
    IPv6.prototype.toByteArray = function() {
      var bytes, part, _i, _len, _ref;
      bytes = [];
      _ref = this.parts;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        part = _ref[_i];
        bytes.push(part >> 8);
        bytes.push(part & 0xff);
      }
      return bytes;
    };
 
    IPv6.prototype.toNormalizedString = function() {
      var part;
      return ((function() {
        var _i, _len, _ref, _results;
        _ref = this.parts;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          part = _ref[_i];
          _results.push(part.toString(16));
        }
        return _results;
      }).call(this)).join(":");
    };
 
    IPv6.prototype.match = function(other, cidrRange) {
      var _ref;
      if (cidrRange === void 0) {
        _ref = other, other = _ref[0], cidrRange = _ref[1];
      }
      if (other.kind() !== 'ipv6') {
        throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
      }
      return matchCIDR(this.parts, other.parts, 16, cidrRange);
    };
 
    IPv6.prototype.SpecialRanges = {
      unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
      linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
      multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
      loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
      uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
      ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
      rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
      rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
      '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
      teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
      reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
    };
 
    IPv6.prototype.range = function() {
      return ipaddr.subnetMatch(this, this.SpecialRanges);
    };
 
    IPv6.prototype.isIPv4MappedAddress = function() {
      return this.range() === 'ipv4Mapped';
    };
 
    IPv6.prototype.toIPv4Address = function() {
      var high, low, _ref;
      if (!this.isIPv4MappedAddress()) {
        throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
      }
      _ref = this.parts.slice(-2), high = _ref[0], low = _ref[1];
      return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
    };
 
    return IPv6;
 
  })();
 
  ipv6Part = "(?:[0-9a-f]+::?)+";
 
  ipv6Regexes = {
    "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?$", 'i'),
    transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + ("" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$"), 'i')
  };
 
  expandIPv6 = function(string, parts) {
    var colonCount, lastColon, part, replacement, replacementCount;
    if (string.indexOf('::') !== string.lastIndexOf('::')) {
      return null;
    }
    colonCount = 0;
    lastColon = -1;
    while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
      colonCount++;
    }
    if (string[0] === ':') {
      colonCount--;
    }
    if (string[string.length - 1] === ':') {
      colonCount--;
    }
    if (colonCount > parts) {
      return null;
    }
    replacementCount = parts - colonCount;
    replacement = ':';
    while (replacementCount--) {
      replacement += '0:';
    }
    string = string.replace('::', replacement);
    if (string[0] === ':') {
      string = string.slice(1);
    }
    if (string[string.length - 1] === ':') {
      string = string.slice(0, -1);
    }
    return (function() {
      var _i, _len, _ref, _results;
      _ref = string.split(":");
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        part = _ref[_i];
        _results.push(parseInt(part, 16));
      }
      return _results;
    })();
  };
 
  ipaddr.IPv6.parser = function(string) {
    var match, parts;
    if (string.match(ipv6Regexes['native'])) {
      return expandIPv6(string, 8);
    } else if (match = string.match(ipv6Regexes['transitional'])) {
      parts = expandIPv6(match[1].slice(0, -1), 6);
      if (parts) {
        parts.push(parseInt(match[2]) << 8 | parseInt(match[3]));
        parts.push(parseInt(match[4]) << 8 | parseInt(match[5]));
        return parts;
      }
    }
    return null;
  };
 
  ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
    return this.parser(string) !== null;
  };
 
  ipaddr.IPv4.isValid = ipaddr.IPv6.isValid = function(string) {
    var e;
    try {
      new this(this.parser(string));
      return true;
    } catch (_error) {
      e = _error;
      return false;
    }
  };
 
  ipaddr.IPv4.parse = ipaddr.IPv6.parse = function(string) {
    var parts;
    parts = this.parser(string);
    if (parts === null) {
      throw new Error("ipaddr: string is not formatted like ip address");
    }
    return new this(parts);
  };
 
  ipaddr.IPv4.parseCIDR = ipaddr.IPv6.parseCIDR = function(string) {
    var match;
    if (match = string.match(/^(.+)\/(\d+)$/)) {
      return [this.parse(match[1]), parseInt(match[2])];
    }
    throw new Error("ipaddr: string is not formatted like a CIDR range");
  };
 
  ipaddr.isValid = function(string) {
    return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
  };
 
  ipaddr.parse = function(string) {
    if (ipaddr.IPv6.isValid(string)) {
      return ipaddr.IPv6.parse(string);
    } else if (ipaddr.IPv4.isValid(string)) {
      return ipaddr.IPv4.parse(string);
    } else {
      throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
    }
  };
 
  ipaddr.parseCIDR = function(string) {
    var e;
    try {
      return ipaddr.IPv6.parseCIDR(string);
    } catch (_error) {
      e = _error;
      try {
        return ipaddr.IPv4.parseCIDR(string);
      } catch (_error) {
        e = _error;
        throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
      }
    }
  };
 
  ipaddr.process = function(string) {
    var addr;
    addr = this.parse(string);
    if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
      return addr.toIPv4Address();
    } else {
      return addr;
    }
  };
 
}).call(this);
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('./lib');
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/

Statements: 13.04% (21 / 161)      Branches: 0% (0 / 115)      Functions: 0% (0 / 12)      Lines: 13.04% (21 / 161)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/
File Statements Branches Functions Lines
index.js 100% (4 / 4) 100% (0 / 0) 100% (0 / 0) 100% (4 / 4)
parse.js 8.96% (6 / 67) 0% (0 / 53) 0% (0 / 4) 8.96% (6 / 67)
stringify.js 12.12% (4 / 33) 0% (0 / 27) 0% (0 / 2) 12.12% (4 / 33)
utils.js 12.28% (7 / 57) 0% (0 / 35) 0% (0 / 6) 12.28% (7 / 57)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/index.js

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17    1 1         1     1          
// Load modules
 
var Stringify = require('./stringify');
var Parse = require('./parse');
 
 
// Declare internals
 
var internals = {};
 
 
module.exports = {
    stringify: Stringify,
    parse: Parse
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/parse.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/parse.js

Statements: 8.96% (6 / 67)      Branches: 0% (0 / 53)      Functions: 0% (0 / 4)      Lines: 8.96% (6 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158    1         1               1                                                         1                                                                   1                                                                                                 1                                                            
// Load modules
 
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {
    delimiter: '&',
    depth: 5,
    arrayLimit: 20,
    parameterLimit: 1000
};
 
 
internals.parseValues = function (str, options) {
 
    var obj = {};
    var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
 
    for (var i = 0, il = parts.length; i < il; ++i) {
        var part = parts[i];
        var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
 
        if (pos === -1) {
            obj[Utils.decode(part)] = '';
        }
        else {
            var key = Utils.decode(part.slice(0, pos));
            var val = Utils.decode(part.slice(pos + 1));
 
            if (!obj.hasOwnProperty(key)) {
                obj[key] = val;
            }
            else {
                obj[key] = [].concat(obj[key]).concat(val);
            }
        }
    }
 
    return obj;
};
 
 
internals.parseObject = function (chain, val, options) {
 
    if (!chain.length) {
        return val;
    }
 
    var root = chain.shift();
 
    var obj = {};
    if (root === '[]') {
        obj = [];
        obj = obj.concat(internals.parseObject(chain, val, options));
    }
    else {
        var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
        var index = parseInt(cleanRoot, 10);
        var indexString = '' + index;
        if (!isNaN(index) &&
            root !== cleanRoot &&
            indexString === cleanRoot &&
            index <= options.arrayLimit) {
 
            obj = [];
            obj[index] = internals.parseObject(chain, val, options);
        }
        else {
            obj[cleanRoot] = internals.parseObject(chain, val, options);
        }
    }
 
    return obj;
};
 
 
internals.parseKeys = function (key, val, options) {
 
    if (!key) {
        return;
    }
 
    // The regex chunks
 
    var parent = /^([^\[\]]*)/;
    var child = /(\[[^\[\]]*\])/g;
 
    // Get the parent
 
    var segment = parent.exec(key);
 
    // Don't allow them to overwrite object prototype properties
 
    if (Object.prototype.hasOwnProperty(segment[1])) {
        return;
    }
 
    // Stash the parent if it exists
 
    var keys = [];
    if (segment[1]) {
        keys.push(segment[1]);
    }
 
    // Loop through children appending to the array until we hit depth
 
    var i = 0;
    while ((segment = child.exec(key)) !== null && i < options.depth) {
 
        ++i;
        if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
            keys.push(segment[1]);
        }
    }
 
    // If there's a remainder, just add whatever is left
 
    if (segment) {
        keys.push('[' + key.slice(segment.index) + ']');
    }
 
    return internals.parseObject(keys, val, options);
};
 
 
module.exports = function (str, options) {
 
    if (str === '' ||
        str === null ||
        typeof str === 'undefined') {
 
        return {};
    }
 
    options = options || {};
    options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter;
    options.depth = typeof options.depth === 'number' ? options.depth : internals.depth;
    options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit;
    options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit;
 
    var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str;
    var obj = {};
 
    // Iterate over the keys and setup the new object
 
    var keys = Object.keys(tempObj);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        var newObj = internals.parseKeys(key, tempObj[key], options);
        obj = Utils.merge(obj, newObj);
    }
 
    return Utils.compact(obj);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/stringify.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/stringify.js

Statements: 12.12% (4 / 33)      Branches: 0% (0 / 27)      Functions: 0% (0 / 2)      Lines: 12.12% (4 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79    1         1           1                                                                                   1                                              
// Load modules
 
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {
    delimiter: '&',
    indices: true
};
 
 
internals.stringify = function (obj, prefix, options) {
 
    if (Utils.isBuffer(obj)) {
        obj = obj.toString();
    }
    else if (obj instanceof Date) {
        obj = obj.toISOString();
    }
    else if (obj === null) {
        obj = '';
    }
 
    if (typeof obj === 'string' ||
        typeof obj === 'number' ||
        typeof obj === 'boolean') {
 
        return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)];
    }
 
    var values = [];
 
    if (typeof obj === 'undefined') {
        return values;
    }
 
    var objKeys = Object.keys(obj);
    for (var i = 0, il = objKeys.length; i < il; ++i) {
        var key = objKeys[i];
        if (!options.indices &&
            Array.isArray(obj)) {
 
            values = values.concat(internals.stringify(obj[key], prefix, options));
        }
        else {
            values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', options));
        }
    }
 
    return values;
};
 
 
module.exports = function (obj, options) {
 
    options = options || {};
    var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
    options.indices = typeof options.indices === 'boolean' ? options.indices : internals.indices;
 
    var keys = [];
 
    if (typeof obj !== 'object' ||
        obj === null) {
 
        return '';
    }
 
    var objKeys = Object.keys(obj);
    for (var i = 0, il = objKeys.length; i < il; ++i) {
        var key = objKeys[i];
        keys = keys.concat(internals.stringify(obj[key], key, options));
    }
 
    return keys.join(delimiter);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/utils.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/qs/lib/utils.js

Statements: 12.28% (7 / 57)      Branches: 0% (0 / 35)      Functions: 0% (0 / 6)      Lines: 12.28% (7 / 57)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134          1     1                           1                                                                                         1                   1                                                                           1         1                          
// Load modules
 
 
// Declare internals
 
var internals = {};
 
 
exports.arrayToObject = function (source) {
 
    var obj = {};
    for (var i = 0, il = source.length; i < il; ++i) {
        if (typeof source[i] !== 'undefined') {
 
            obj[i] = source[i];
        }
    }
 
    return obj;
};
 
 
exports.merge = function (target, source) {
 
    if (!source) {
        return target;
    }
 
    if (typeof source !== 'object') {
        if (Array.isArray(target)) {
            target.push(source);
        }
        else {
            target[source] = true;
        }
 
        return target;
    }
 
    if (typeof target !== 'object') {
        target = [target].concat(source);
        return target;
    }
 
    if (Array.isArray(target) &&
        !Array.isArray(source)) {
 
        target = exports.arrayToObject(target);
    }
 
    var keys = Object.keys(source);
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var value = source[key];
 
        if (!target[key]) {
            target[key] = value;
        }
        else {
            target[key] = exports.merge(target[key], value);
        }
    }
 
    return target;
};
 
 
exports.decode = function (str) {
 
    try {
        return decodeURIComponent(str.replace(/\+/g, ' '));
    } catch (e) {
        return str;
    }
};
 
 
exports.compact = function (obj, refs) {
 
    if (typeof obj !== 'object' ||
        obj === null) {
 
        return obj;
    }
 
    refs = refs || [];
    var lookup = refs.indexOf(obj);
    if (lookup !== -1) {
        return refs[lookup];
    }
 
    refs.push(obj);
 
    if (Array.isArray(obj)) {
        var compacted = [];
 
        for (var i = 0, l = obj.length; i < l; ++i) {
            if (typeof obj[i] !== 'undefined') {
                compacted.push(obj[i]);
            }
        }
 
        return compacted;
    }
 
    var keys = Object.keys(obj);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        obj[key] = exports.compact(obj[key], refs);
    }
 
    return obj;
};
 
 
exports.isRegExp = function (obj) {
    return Object.prototype.toString.call(obj) === '[object RegExp]';
};
 
 
exports.isBuffer = function (obj) {
 
    if (obj === null ||
        typeof obj === 'undefined') {
 
        return false;
    }
 
    return !!(obj.constructor &&
        obj.constructor.isBuffer &&
        obj.constructor.isBuffer(obj));
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/range-parser/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/range-parser/

Statements: 5.26% (1 / 19)      Branches: 0% (0 / 16)      Functions: 0% (0 / 2)      Lines: 5.88% (1 / 17)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/range-parser/
File Statements Branches Functions Lines
index.js 5.26% (1 / 19) 0% (0 / 16) 0% (0 / 2) 5.88% (1 / 17)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/range-parser/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/range-parser/index.js

Statements: 5.26% (1 / 19)      Branches: 0% (0 / 16)      Functions: 0% (0 / 2)      Lines: 5.88% (1 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                    1                                                                                
 
/**
 * Parse "Range" header `str` relative to the given file `size`.
 *
 * @param {Number} size
 * @param {String} str
 * @return {Array}
 * @api public
 */
 
module.exports = function(size, str){
  var valid = true;
  var i = str.indexOf('=');
 
  if (-1 == i) return -2;
 
  var arr = str.slice(i + 1).split(',').map(function(range){
    var range = range.split('-')
      , start = parseInt(range[0], 10)
      , end = parseInt(range[1], 10);
 
    // -nnn
    if (isNaN(start)) {
      start = size - end;
      end = size - 1;
    // nnn-
    } else if (isNaN(end)) {
      end = size - 1;
    }
 
    // limit last-byte-pos to current length
    if (end > size - 1) end = size - 1;
 
    // invalid
    if (isNaN(start)
      || isNaN(end)
      || start > end
      || start < 0) valid = false;
 
    return {
      start: start,
      end: end
    };
  });
 
  arr.type = str.slice(0, i);
 
  return valid ? arr : -1;
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/

Statements: 16.83% (51 / 303)      Branches: 1.22% (2 / 164)      Functions: 2.63% (1 / 38)      Lines: 18.09% (51 / 282)      Ignored: 1 statement, 1 function, 1 branch     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/
File Statements Branches Functions Lines
index.js 16.83% (51 / 303) 1.22% (2 / 164) 2.63% (1 / 38) 18.09% (51 / 282)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/index.js

Statements: 16.83% (51 / 303)      Branches: 1.22% (2 / 164)      Functions: 2.63% (1 / 38)      Lines: 18.09% (51 / 282)      Ignored: 1 statement, 1 function, 1 branch     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775          1 1 1 1                   1 1 1 1         1 1 1 1 1 1           1           1             1 1                       1                         1                                                                                                                             1                   1                             1                                 1                             1           1     1                     1                                   1                                                   1                     1                     1                             1                           1                           1                       1                         1                     1                                 1                                           1                                                                                                                                                                     1                                                                                                                                                                           1                                   1                                                 1       1                                                       1                                                                                         1                                   1                                                       1                                       1                             1        
 
/**
 * Module dependencies.
 */
 
var debug = require('debug')('send')
var deprecate = require('depd')('send')
var destroy = require('destroy')
var escapeHtml = require('escape-html')
  , parseRange = require('range-parser')
  , Stream = require('stream')
  , mime = require('mime')
  , fresh = require('fresh')
  , path = require('path')
  , http = require('http')
  , fs = require('fs')
  , normalize = path.normalize
  , join = path.join
var etag = require('etag')
var EventEmitter = require('events').EventEmitter;
var ms = require('ms');
var onFinished = require('on-finished')
 
/**
 * Variables.
 */
var extname = path.extname
var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year
var resolve = path.resolve
var sep = path.sep
var toString = Object.prototype.toString
var upPathRegexp = /(?:^|[\\\/])\.\.(?:[\\\/]|$)/
 
/**
 * Expose `send`.
 */
 
exports = module.exports = send;
 
/**
 * Expose mime module.
 */
 
exports.mime = mime;
 
/**
 * Shim EventEmitter.listenerCount for node.js < 0.10
 */
 
/* istanbul ignore next */
var listenerCount = EventEmitter.listenerCount
  || function(emitter, type){ return emitter.listeners(type).length; };
 
/**
 * Return a `SendStream` for `req` and `path`.
 *
 * @param {Request} req
 * @param {String} path
 * @param {Object} options
 * @return {SendStream}
 * @api public
 */
 
function send(req, path, options) {
  return new SendStream(req, path, options);
}
 
/**
 * Initialize a `SendStream` with the given `path`.
 *
 * @param {Request} req
 * @param {String} path
 * @param {Object} options
 * @api private
 */
 
function SendStream(req, path, options) {
  var self = this;
  options = options || {};
  this.req = req;
  this.path = path;
  this.options = options;
 
  this._etag = options.etag !== undefined
    ? Boolean(options.etag)
    : true
 
  this._dotfiles = options.dotfiles !== undefined
    ? options.dotfiles
    : 'ignore'
 
  if (['allow', 'deny', 'ignore'].indexOf(this._dotfiles) === -1) {
    throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"')
  }
 
  this._hidden = Boolean(options.hidden)
 
  if ('hidden' in options) {
    deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead')
  }
 
  // legacy support
  if (!('dotfiles' in options)) {
    this._dotfiles = undefined
  }
 
  this._extensions = options.extensions !== undefined
    ? normalizeList(options.extensions)
    : []
 
  this._index = options.index !== undefined
    ? normalizeList(options.index)
    : ['index.html']
 
  this._lastModified = options.lastModified !== undefined
    ? Boolean(options.lastModified)
    : true
 
  this._maxage = options.maxAge || options.maxage
  this._maxage = typeof this._maxage === 'string'
    ? ms(this._maxage)
    : Number(this._maxage)
  this._maxage = !isNaN(this._maxage)
    ? Math.min(Math.max(0, this._maxage), maxMaxAge)
    : 0
 
  this._root = options.root
    ? resolve(options.root)
    : null
 
  if (!this._root && options.from) {
    this.from(options.from);
  }
}
 
/**
 * Inherits from `Stream.prototype`.
 */
 
SendStream.prototype.__proto__ = Stream.prototype;
 
/**
 * Enable or disable etag generation.
 *
 * @param {Boolean} val
 * @return {SendStream}
 * @api public
 */
 
SendStream.prototype.etag = deprecate.function(function etag(val) {
  val = Boolean(val);
  debug('etag %s', val);
  this._etag = val;
  return this;
}, 'send.etag: pass etag as option');
 
/**
 * Enable or disable "hidden" (dot) files.
 *
 * @param {Boolean} path
 * @return {SendStream}
 * @api public
 */
 
SendStream.prototype.hidden = deprecate.function(function hidden(val) {
  val = Boolean(val);
  debug('hidden %s', val);
  this._hidden = val;
  this._dotfiles = undefined
  return this;
}, 'send.hidden: use dotfiles option');
 
/**
 * Set index `paths`, set to a falsy
 * value to disable index support.
 *
 * @param {String|Boolean|Array} paths
 * @return {SendStream}
 * @api public
 */
 
SendStream.prototype.index = deprecate.function(function index(paths) {
  var index = !paths ? [] : normalizeList(paths);
  debug('index %o', paths);
  this._index = index;
  return this;
}, 'send.index: pass index as option');
 
/**
 * Set root `path`.
 *
 * @param {String} path
 * @return {SendStream}
 * @api public
 */
 
SendStream.prototype.root = function(path){
  path = String(path);
  this._root = resolve(path)
  return this;
};
 
SendStream.prototype.from = deprecate.function(SendStream.prototype.root,
  'send.from: pass root as option');
 
SendStream.prototype.root = deprecate.function(SendStream.prototype.root,
  'send.root: pass root as option');
 
/**
 * Set max-age to `maxAge`.
 *
 * @param {Number} maxAge
 * @return {SendStream}
 * @api public
 */
 
SendStream.prototype.maxage = deprecate.function(function maxage(maxAge) {
  maxAge = typeof maxAge === 'string'
    ? ms(maxAge)
    : Number(maxAge);
  if (isNaN(maxAge)) maxAge = 0;
  if (Infinity == maxAge) maxAge = 60 * 60 * 24 * 365 * 1000;
  debug('max-age %d', maxAge);
  this._maxage = maxAge;
  return this;
}, 'send.maxage: pass maxAge as option');
 
/**
 * Emit error with `status`.
 *
 * @param {Number} status
 * @api private
 */
 
SendStream.prototype.error = function(status, err){
  var res = this.res;
  var msg = http.STATUS_CODES[status];
 
  err = err || new Error(msg);
  err.status = status;
 
  // emit if listeners instead of responding
  if (listenerCount(this, 'error') !== 0) {
    return this.emit('error', err);
  }
 
  // wipe all existing headers
  res._headers = undefined;
 
  res.statusCode = err.status;
  res.end(msg);
};
 
/**
 * Check if the pathname ends with "/".
 *
 * @return {Boolean}
 * @api private
 */
 
SendStream.prototype.hasTrailingSlash = function(){
  return '/' == this.path[this.path.length - 1];
};
 
/**
 * Check if this is a conditional GET request.
 *
 * @return {Boolean}
 * @api private
 */
 
SendStream.prototype.isConditionalGET = function(){
  return this.req.headers['if-none-match']
    || this.req.headers['if-modified-since'];
};
 
/**
 * Strip content-* header fields.
 *
 * @api private
 */
 
SendStream.prototype.removeContentHeaderFields = function(){
  var res = this.res;
  Object.keys(res._headers).forEach(function(field){
    if (0 == field.indexOf('content')) {
      res.removeHeader(field);
    }
  });
};
 
/**
 * Respond with 304 not modified.
 *
 * @api private
 */
 
SendStream.prototype.notModified = function(){
  var res = this.res;
  debug('not modified');
  this.removeContentHeaderFields();
  res.statusCode = 304;
  res.end();
};
 
/**
 * Raise error that headers already sent.
 *
 * @api private
 */
 
SendStream.prototype.headersAlreadySent = function headersAlreadySent(){
  var err = new Error('Can\'t set headers after they are sent.');
  debug('headers already sent');
  this.error(500, err);
};
 
/**
 * Check if the request is cacheable, aka
 * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}).
 *
 * @return {Boolean}
 * @api private
 */
 
SendStream.prototype.isCachable = function(){
  var res = this.res;
  return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode;
};
 
/**
 * Handle stat() error.
 *
 * @param {Error} err
 * @api private
 */
 
SendStream.prototype.onStatError = function(err){
  var notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'];
  if (~notfound.indexOf(err.code)) return this.error(404, err);
  this.error(500, err);
};
 
/**
 * Check if the cache is fresh.
 *
 * @return {Boolean}
 * @api private
 */
 
SendStream.prototype.isFresh = function(){
  return fresh(this.req.headers, this.res._headers);
};
 
/**
 * Check if the range is fresh.
 *
 * @return {Boolean}
 * @api private
 */
 
SendStream.prototype.isRangeFresh = function isRangeFresh(){
  var ifRange = this.req.headers['if-range'];
 
  if (!ifRange) return true;
 
  return ~ifRange.indexOf('"')
    ? ~ifRange.indexOf(this.res._headers['etag'])
    : Date.parse(this.res._headers['last-modified']) <= Date.parse(ifRange);
};
 
/**
 * Redirect to `path`.
 *
 * @param {String} path
 * @api private
 */
 
SendStream.prototype.redirect = function(path){
  if (listenerCount(this, 'directory') !== 0) {
    return this.emit('directory');
  }
 
  if (this.hasTrailingSlash()) return this.error(403);
  var res = this.res;
  path += '/';
  res.statusCode = 301;
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.setHeader('Location', path);
  res.end('Redirecting to <a href="' + escapeHtml(path) + '">' + escapeHtml(path) + '</a>\n');
};
 
/**
 * Pipe to `res.
 *
 * @param {Stream} res
 * @return {Stream} res
 * @api public
 */
 
SendStream.prototype.pipe = function(res){
  var self = this
    , args = arguments
    , root = this._root;
 
  // references
  this.res = res;
 
  // decode the path
  var path = decode(this.path)
  if (path === -1) return this.error(400)
 
  // null byte(s)
  if (~path.indexOf('\0')) return this.error(400);
 
  var parts
  if (root !== null) {
    // join / normalize from optional root dir
    path = normalize(join(root, path))
    root = normalize(root + sep)
 
    // malicious path
    if ((path + sep).substr(0, root.length) !== root) {
      debug('malicious path "%s"', path)
      return this.error(403)
    }
 
    // explode path parts
    parts = path.substr(root.length).split(sep)
  } else {
    // ".." is malicious without "root"
    if (upPathRegexp.test(path)) {
      debug('malicious path "%s"', path)
      return this.error(403)
    }
 
    // explode path parts
    parts = normalize(path).split(sep)
 
    // resolve the path
    path = resolve(path)
  }
 
  // dotfile handling
  if (containsDotFile(parts)) {
    var access = this._dotfiles
 
    // legacy support
    if (access === undefined) {
      access = parts[parts.length - 1][0] === '.'
        ? (this._hidden ? 'allow' : 'ignore')
        : 'allow'
    }
 
    debug('%s dotfile "%s"', access, path)
    switch (access) {
      case 'allow':
        break
      case 'deny':
        return this.error(403)
      case 'ignore':
      default:
        return this.error(404)
    }
  }
 
  // index file support
  if (this._index.length && this.path[this.path.length - 1] === '/') {
    this.sendIndex(path);
    return res;
  }
 
  this.sendFile(path);
  return res;
};
 
/**
 * Transfer `path`.
 *
 * @param {String} path
 * @api public
 */
 
SendStream.prototype.send = function(path, stat){
  var options = this.options;
  var len = stat.size;
  var res = this.res;
  var req = this.req;
  var ranges = req.headers.range;
  var offset = options.start || 0;
 
  if (res._header) {
    // impossible to send now
    return this.headersAlreadySent();
  }
 
  debug('pipe "%s"', path)
 
  // set header fields
  this.setHeader(path, stat);
 
  // set content-type
  this.type(path);
 
  // conditional GET support
  if (this.isConditionalGET()
    && this.isCachable()
    && this.isFresh()) {
    return this.notModified();
  }
 
  // adjust len to start/end options
  len = Math.max(0, len - offset);
  if (options.end !== undefined) {
    var bytes = options.end - offset + 1;
    if (len > bytes) len = bytes;
  }
 
  // Range support
  if (ranges) {
    ranges = parseRange(len, ranges);
 
    // If-Range support
    if (!this.isRangeFresh()) {
      debug('range stale');
      ranges = -2;
    }
 
    // unsatisfiable
    if (-1 == ranges) {
      debug('range unsatisfiable');
      res.setHeader('Content-Range', 'bytes */' + stat.size);
      return this.error(416);
    }
 
    // valid (syntactically invalid/multiple ranges are treated as a regular response)
    if (-2 != ranges && ranges.length === 1) {
      debug('range %j', ranges);
 
      options.start = offset + ranges[0].start;
      options.end = offset + ranges[0].end;
 
      // Content-Range
      res.statusCode = 206;
      res.setHeader('Content-Range', 'bytes '
        + ranges[0].start
        + '-'
        + ranges[0].end
        + '/'
        + len);
      len = options.end - options.start + 1;
    }
  }
 
  // content-length
  res.setHeader('Content-Length', len);
 
  // HEAD support
  if ('HEAD' == req.method) return res.end();
 
  this.stream(path, options);
};
 
/**
 * Transfer file for `path`.
 *
 * @param {String} path
 * @api private
 */
SendStream.prototype.sendFile = function sendFile(path) {
  var i = 0
  var self = this
 
  debug('stat "%s"', path);
  fs.stat(path, function onstat(err, stat) {
    if (err && err.code === 'ENOENT'
      && !extname(path)
      && path[path.length - 1] !== sep) {
      // not found, check extensions
      return next(err)
    }
    if (err) return self.onStatError(err)
    if (stat.isDirectory()) return self.redirect(self.path)
    self.emit('file', path, stat)
    self.send(path, stat)
  })
 
  function next(err) {
    if (self._extensions.length <= i) {
      return err
        ? self.onStatError(err)
        : self.error(404)
    }
 
    var p = path + '.' + self._extensions[i++]
 
    debug('stat "%s"', p)
    fs.stat(p, function (err, stat) {
      if (err) return next(err)
      if (stat.isDirectory()) return next()
      self.emit('file', p, stat)
      self.send(p, stat)
    })
  }
}
 
/**
 * Transfer index for `path`.
 *
 * @param {String} path
 * @api private
 */
SendStream.prototype.sendIndex = function sendIndex(path){
  var i = -1;
  var self = this;
 
  function next(err){
    if (++i >= self._index.length) {
      if (err) return self.onStatError(err);
      return self.error(404);
    }
 
    var p = join(path, self._index[i]);
 
    debug('stat "%s"', p);
    fs.stat(p, function(err, stat){
      if (err) return next(err);
      if (stat.isDirectory()) return next();
      self.emit('file', p, stat);
      self.send(p, stat);
    });
  }
 
  next();
};
 
/**
 * Stream `path` to the response.
 *
 * @param {String} path
 * @param {Object} options
 * @api private
 */
 
SendStream.prototype.stream = function(path, options){
  // TODO: this is all lame, refactor meeee
  var finished = false;
  var self = this;
  var res = this.res;
  var req = this.req;
 
  // pipe
  var stream = fs.createReadStream(path, options);
  this.emit('stream', stream);
  stream.pipe(res);
 
  // response finished, done with the fd
  onFinished(res, function onfinished(){
    finished = true;
    destroy(stream);
  });
 
  // error handling code-smell
  stream.on('error', function onerror(err){
    // request already finished
    if (finished) return;
 
    // clean up stream
    finished = true;
    destroy(stream);
 
    // error
    self.onStatError(err);
  });
 
  // end
  stream.on('end', function onend(){
    self.emit('end');
  });
};
 
/**
 * Set content-type based on `path`
 * if it hasn't been explicitly set.
 *
 * @param {String} path
 * @api private
 */
 
SendStream.prototype.type = function(path){
  var res = this.res;
  if (res.getHeader('Content-Type')) return;
  var type = mime.lookup(path);
  var charset = mime.charsets.lookup(type);
  debug('content-type %s', type);
  res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
};
 
/**
 * Set response header fields, most
 * fields may be pre-defined.
 *
 * @param {String} path
 * @param {Object} stat
 * @api private
 */
 
SendStream.prototype.setHeader = function setHeader(path, stat){
  var res = this.res;
 
  this.emit('headers', res, path, stat);
 
  if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes');
  if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString());
  if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + Math.floor(this._maxage / 1000));
 
  if (this._lastModified && !res.getHeader('Last-Modified')) {
    var modified = stat.mtime.toUTCString()
    debug('modified %s', modified)
    res.setHeader('Last-Modified', modified)
  }
 
  if (this._etag && !res.getHeader('ETag')) {
    var val = etag(stat)
    debug('etag %s', val)
    res.setHeader('ETag', val)
  }
};
 
/**
 * Determine if path parts contain a dotfile.
 *
 * @api private
 */
 
function containsDotFile(parts) {
  for (var i = 0; i < parts.length; i++) {
    if (parts[i][0] === '.') {
      return true
    }
  }
 
  return false
}
 
/**
 * decodeURIComponent.
 *
 * Allows V8 to only deoptimize this fn instead of all
 * of send().
 *
 * @param {String} path
 * @api private
 */
 
function decode(path) {
  try {
    return decodeURIComponent(path)
  } catch (err) {
    return -1
  }
}
 
/**
 * Normalize the index option into an array.
 *
 * @param {boolean|string|array} val
 * @api private
 */
 
function normalizeList(val){
  return [].concat(val || [])
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/destroy/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/destroy/

Statements: 27.78% (5 / 18)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 27.78% (5 / 18)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/destroy/
File Statements Branches Functions Lines
index.js 27.78% (5 / 18) 0% (0 / 10) 0% (0 / 3) 27.78% (5 / 18)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/destroy/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/destroy/index.js

Statements: 27.78% (5 / 18)      Branches: 0% (0 / 10)      Functions: 0% (0 / 3)      Lines: 27.78% (5 / 18)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 381 1   1                               1                     1              
var ReadStream = require('fs').ReadStream
var Stream = require('stream')
 
module.exports = function destroy(stream) {
  if (stream instanceof ReadStream) {
    return destroyReadStream(stream)
  }
 
  if (!(stream instanceof Stream)) {
    return stream
  }
 
  if (typeof stream.destroy === 'function') {
    stream.destroy()
  }
 
  return stream
}
 
function destroyReadStream(stream) {
  stream.destroy()
 
  if (typeof stream.close === 'function') {
    // node.js core bug work-around
    stream.on('open', onopenClose)
  }
 
  return stream
}
 
function onopenClose() {
  if (typeof this.fd === 'number') {
    // actually close down the fd
    this.close()
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/mime/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/mime/

Statements: 88.89% (32 / 36)      Branches: 45.45% (5 / 11)      Functions: 71.43% (5 / 7)      Lines: 88.89% (32 / 36)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/mime/
File Statements Branches Functions Lines
mime.js 88.89% (32 / 36) 45.45% (5 / 11) 71.43% (5 / 7) 88.89% (32 / 36)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/mime/mime.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/mime/mime.js

Statements: 88.89% (32 / 36)      Branches: 45.45% (5 / 11)      Functions: 71.43% (5 / 7)      Lines: 88.89% (32 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 1161 1   1   1     1                       1 2 783   783 1001         1001       783 778                         1   2   2       2   1654 1654     2   2           1 1   1           1           1       1     1     1           1         1             1    
var path = require('path');
var fs = require('fs');
 
function Mime() {
  // Map of extension -> mime type
  this.types = Object.create(null);
 
  // Map of mime type -> extension
  this.extensions = Object.create(null);
}
 
/**
 * Define mimetype -> extension mappings.  Each key is a mime-type that maps
 * to an array of extensions associated with the type.  The first extension is
 * used as the default extension for the type.
 *
 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
 *
 * @param map (Object) type definitions
 */
Mime.prototype.define = function (map) {
  for (var type in map) {
    var exts = map[type];
 
    for (var i = 0; i < exts.length; i++) {
      Iif (process.env.DEBUG_MIME && this.types[exts]) {
        console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
          this.types[exts] + ' to ' + type);
      }
 
      this.types[exts[i]] = type;
    }
 
    // Default extension is the first one we encounter
    if (!this.extensions[type]) {
      this.extensions[type] = exts[0];
    }
  }
};
 
/**
 * Load an Apache2-style ".types" file
 *
 * This may be called multiple times (it's expected).  Where files declare
 * overlapping types/extensions, the last file wins.
 *
 * @param file (String) path of file to load.
 */
Mime.prototype.load = function(file) {
 
  this._loading = file;
  // Read file and split into lines
  var map = {},
      content = fs.readFileSync(file, 'ascii'),
      lines = content.split(/[\r\n]+/);
 
  lines.forEach(function(line) {
    // Clean up whitespace/comments, and split into fields
    var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
    map[fields.shift()] = fields;
  });
 
  this.define(map);
 
  this._loading = null;
};
 
/**
 * Lookup a mime type based on extension
 */
Mime.prototype.lookup = function(path, fallback) {
  var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase();
 
  return this.types[ext] || fallback || this.default_type;
};
 
/**
 * Return file extension associated with a mime type
 */
Mime.prototype.extension = function(mimeType) {
  var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
  return this.extensions[type];
};
 
// Default instance
var mime = new Mime();
 
// Load local copy of
// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
mime.load(path.join(__dirname, 'types/mime.types'));
 
// Load additional types from node.js community
mime.load(path.join(__dirname, 'types/node.types'));
 
// Default type
mime.default_type = mime.lookup('bin');
 
//
// Additional API specific to the default instance
//
 
mime.Mime = Mime;
 
/**
 * Lookup a charset based on mime type.
 */
mime.charsets = {
  lookup: function(mimeType, fallback) {
    // Assume text types are utf8
    return (/^text\//).test(mimeType) ? 'UTF-8' : fallback;
  }
};
 
module.exports = mime;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/ms/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/ms/

Statements: 24.39% (10 / 41)      Branches: 0% (0 / 43)      Functions: 0% (0 / 5)      Lines: 30.3% (10 / 33)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/ms/
File Statements Branches Functions Lines
index.js 24.39% (10 / 41) 0% (0 / 43) 0% (0 / 5) 30.3% (10 / 33)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/ms/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/send/node_modules/ms/index.js

Statements: 24.39% (10 / 41)      Branches: 0% (0 / 43)      Functions: 0% (0 / 5)      Lines: 30.3% (10 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113        1 1 1 1 1                             1                               1                                                                             1                               1                       1            
/**
 * Helpers.
 */
 
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
 
/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} options
 * @return {String|Number}
 * @api public
 */
 
module.exports = function(val, options){
  options = options || {};
  if ('string' == typeof val) return parse(val);
  return options.long
    ? long(val)
    : short(val);
};
 
/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */
 
function parse(str) {
  var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  if (!match) return;
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'y':
      return n * y;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 's':
      return n * s;
    case 'ms':
      return n;
  }
}
 
/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function short(ms) {
  if (ms >= d) return Math.round(ms / d) + 'd';
  if (ms >= h) return Math.round(ms / h) + 'h';
  if (ms >= m) return Math.round(ms / m) + 'm';
  if (ms >= s) return Math.round(ms / s) + 's';
  return ms + 'ms';
}
 
/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */
 
function long(ms) {
  return plural(ms, d, 'day')
    || plural(ms, h, 'hour')
    || plural(ms, m, 'minute')
    || plural(ms, s, 'second')
    || ms + ' ms';
}
 
/**
 * Pluralization helper.
 */
 
function plural(ms, n, name) {
  if (ms < n) return;
  if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  return Math.ceil(ms / n) + ' ' + name + 's';
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/serve-static/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/serve-static/

Statements: 17.31% (9 / 52)      Branches: 0% (0 / 31)      Functions: 0% (0 / 5)      Lines: 17.31% (9 / 52)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/serve-static/
File Statements Branches Functions Lines
index.js 17.31% (9 / 52) 0% (0 / 31) 0% (0 / 5) 17.31% (9 / 52)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/serve-static/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/serve-static/index.js

Statements: 17.31% (9 / 52)      Branches: 0% (0 / 31)      Functions: 0% (0 / 5)      Lines: 17.31% (9 / 52)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139                        1 1 1 1 1 1                 1                                                                                                                                                                                           1           1                        
/*!
 * serve-static
 * Copyright(c) 2010 Sencha Inc.
 * Copyright(c) 2011 TJ Holowaychuk
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 */
 
var escapeHtml = require('escape-html');
var merge = require('utils-merge');
var parseurl = require('parseurl');
var resolve = require('path').resolve;
var send = require('send');
var url = require('url');
 
/**
 * @param {String} root
 * @param {Object} options
 * @return {Function}
 * @api public
 */
 
exports = module.exports = function serveStatic(root, options) {
  if (!root) {
    throw new TypeError('root path required')
  }
 
  if (typeof root !== 'string') {
    throw new TypeError('root path must be a string')
  }
 
  // copy options object
  options = merge({}, options)
 
  // resolve root to absolute
  root = resolve(root)
 
  // default redirect
  var redirect = options.redirect !== false
 
  // headers listener
  var setHeaders = options.setHeaders
  delete options.setHeaders
 
  if (setHeaders && typeof setHeaders !== 'function') {
    throw new TypeError('option setHeaders must be function')
  }
 
  // setup options for send
  options.maxage = options.maxage || options.maxAge || 0
  options.root = root
 
  return function serveStatic(req, res, next) {
    if (req.method !== 'GET' && req.method !== 'HEAD') {
      return next()
    }
 
    var opts = merge({}, options)
    var originalUrl = parseurl.original(req)
    var path = parseurl(req).pathname
    var hasTrailingSlash = originalUrl.pathname[originalUrl.pathname.length - 1] === '/'
 
    if (path === '/' && !hasTrailingSlash) {
      // make sure redirect occurs at mount
      path = ''
    }
 
    // create send stream
    var stream = send(req, path, opts)
 
    if (redirect) {
      // redirect relative to originalUrl
      stream.on('directory', function redirect() {
        if (hasTrailingSlash) {
          return next()
        }
 
        // append trailing slash
        originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/')
 
        // reformat the URL
        var target = url.format(originalUrl)
 
        // send redirect response
        res.statusCode = 303
        res.setHeader('Content-Type', 'text/html; charset=utf-8')
        res.setHeader('Location', target)
        res.end('Redirecting to <a href="' + escapeHtml(target) + '">' + escapeHtml(target) + '</a>\n')
      })
    } else {
      // forward to next middleware on directory
      stream.on('directory', next)
    }
 
    // add headers listener
    if (setHeaders) {
      stream.on('headers', setHeaders)
    }
 
    // forward non-404 errors
    stream.on('error', function error(err) {
      next(err.status === 404 ? null : err)
    })
 
    // pipe
    stream.pipe(res)
  }
}
 
/**
 * Expose mime module.
 *
 * If you wish to extend the mime table use this
 * reference to the "mime" module in the npm registry.
 */
 
exports.mime = send.mime
 
/**
 * Collapse all leading slashes into a single slash
 * @private
 */
function collapseLeadingSlashes(str) {
  for (var i = 0; i < str.length; i++) {
    if (str[i] !== '/') {
      break
    }
  }
 
  return i > 1
    ? '/' + str.substr(i)
    : str
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/

Statements: 18.84% (13 / 69)      Branches: 0% (0 / 50)      Functions: 0% (0 / 6)      Lines: 19.4% (13 / 67)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/
File Statements Branches Functions Lines
index.js 18.84% (13 / 69) 0% (0 / 50) 0% (0 / 6) 19.4% (13 / 67)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/index.js

Statements: 18.84% (13 / 69)      Branches: 0% (0 / 50)      Functions: 0% (0 / 6)      Lines: 19.4% (13 / 67)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230  1 1   1 1 1 1 1                               1                                                                                                 1                                                               1                                                                           1                                               1                                                                                                       1                    
 
var typer = require('media-typer')
var mime = require('mime-types')
 
module.exports = typeofrequest;
typeofrequest.is = typeis;
typeofrequest.hasBody = hasbody;
typeofrequest.normalize = normalize;
typeofrequest.match = mimeMatch;
 
/**
 * Compare a `value` content-type with `types`.
 * Each `type` can be an extension like `html`,
 * a special shortcut like `multipart` or `urlencoded`,
 * or a mime type.
 *
 * If no types match, `false` is returned.
 * Otherwise, the first `type` that matches is returned.
 *
 * @param {String} value
 * @param {Array} types
 * @return String
 */
 
function typeis(value, types_) {
  var i
  var types = types_
 
  // remove parameters and normalize
  var val = typenormalize(value)
 
  // no type or invalid
  if (!val) {
    return false
  }
 
  // support flattened arguments
  if (types && !Array.isArray(types)) {
    types = new Array(arguments.length - 1)
    for (i = 0; i < types.length; i++) {
      types[i] = arguments[i + 1]
    }
  }
 
  // no types, return the content type
  if (!types || !types.length) {
    return val
  }
 
  var type
  for (i = 0; i < types.length; i++) {
    if (mimeMatch(normalize(type = types[i]), val)) {
      return type[0] === '+' || ~type.indexOf('*')
        ? val
        : type
    }
  }
 
  // no matches
  return false;
}
 
/**
 * Check if a request has a request body.
 * A request with a body __must__ either have `transfer-encoding`
 * or `content-length` headers set.
 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
 *
 * @param {Object} request
 * @return {Boolean}
 * @api public
 */
 
function hasbody(req) {
  var headers = req.headers;
  if ('transfer-encoding' in headers) return true;
  return !isNaN(headers['content-length']);
}
 
/**
 * Check if the incoming request contains the "Content-Type"
 * header field, and it contains any of the give mime `type`s.
 * If there is no request body, `null` is returned.
 * If there is no content type, `false` is returned.
 * Otherwise, it returns the first `type` that matches.
 *
 * Examples:
 *
 *     // With Content-Type: text/html; charset=utf-8
 *     this.is('html'); // => 'html'
 *     this.is('text/html'); // => 'text/html'
 *     this.is('text/*', 'application/json'); // => 'text/html'
 *
 *     // When Content-Type is application/json
 *     this.is('json', 'urlencoded'); // => 'json'
 *     this.is('application/json'); // => 'application/json'
 *     this.is('html', 'application/*'); // => 'application/json'
 *
 *     this.is('html'); // => false
 *
 * @param {String|Array} types...
 * @return {String|false|null}
 * @api public
 */
 
function typeofrequest(req, types_) {
  var types = types_
 
  // no body
  if (!hasbody(req)) {
    return null
  }
 
  // support flattened arguments
  if (arguments.length > 2) {
    types = new Array(arguments.length - 1)
    for (var i = 0; i < types.length; i++) {
      types[i] = arguments[i + 1]
    }
  }
 
  // request content type
  var value = req.headers['content-type']
 
  return typeis(value, types);
}
 
/**
 * Normalize a mime type.
 * If it's a shorthand, expand it to a valid mime type.
 *
 * In general, you probably want:
 *
 *   var type = is(req, ['urlencoded', 'json', 'multipart']);
 *
 * Then use the appropriate body parsers.
 * These three are the most common request body types
 * and are thus ensured to work.
 *
 * @param {String} type
 * @api private
 */
 
function normalize(type) {
  switch (type) {
    case 'urlencoded': return 'application/x-www-form-urlencoded';
    case 'multipart':
      type = 'multipart/*';
      break;
  }
 
  return type[0] === '+' || ~type.indexOf('/')
    ? type
    : mime.lookup(type)
}
 
/**
 * Check if `exected` mime type
 * matches `actual` mime type with
 * wildcard and +suffix support.
 *
 * @param {String} expected
 * @param {String} actual
 * @return {Boolean}
 * @api private
 */
 
function mimeMatch(expected, actual) {
  // invalid type
  if (expected === false) {
    return false
  }
 
  // exact match
  if (expected === actual) {
    return true
  }
 
  actual = actual.split('/');
 
  if (expected[0] === '+') {
    // support +suffix
    return Boolean(actual[1])
      && expected.length <= actual[1].length
      && expected === actual[1].substr(0 - expected.length)
  }
 
  if (!~expected.indexOf('*')) return false;
 
  expected = expected.split('/');
 
  if (expected[0] === '*') {
    // support */yyy
    return expected[1] === actual[1]
  }
 
  if (expected[1] === '*') {
    // support xxx/*
    return expected[0] === actual[0]
  }
 
  if (expected[1][0] === '*' && expected[1][1] === '+') {
    // support xxx/*+zzz
    return expected[0] === actual[0]
      && expected[1].length <= actual[1].length + 1
      && expected[1].substr(1) === actual[1].substr(1 - expected[1].length)
  }
 
  return false
}
 
/**
 * Normalize a type and remove parameters.
 *
 * @param {string} value
 * @return {string}
 * @api private
 */
 
function typenormalize(value) {
  try {
    var type = typer.parse(value)
    delete type.parameters
    return typer.format(type)
  } catch (err) {
    return null
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/
File Statements Branches Functions Lines
index.js 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/index.js

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  1     1   1   1 1799 1799 1799 789 789 1018       1               1                     1                     1         1                      
 
var db = require('mime-db')
 
// types[extension] = type
exports.types = Object.create(null)
// extensions[type] = [extensions]
exports.extensions = Object.create(null)
 
Object.keys(db).forEach(function (name) {
  var mime = db[name]
  var exts = mime.extensions
  if (!exts || !exts.length) return
  exports.extensions[name] = exts
  exts.forEach(function (ext) {
    exports.types[ext] = name
  })
})
 
exports.lookup = function (string) {
  if (!string || typeof string !== "string") return false
  // remove any leading paths, though we should just use path.basename
  string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
  if (!string) return false
  return exports.types[string] || false
}
 
exports.extension = function (type) {
  if (!type || typeof type !== "string") return false
  // to do: use media-typer
  type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
  if (!type) return false
  var exts = exports.extensions[type[1].toLowerCase()]
  if (!exts || !exts.length) return false
  return exts[0]
}
 
// type has to be an exact mime type
exports.charset = function (type) {
  var mime = db[type]
  if (mime && mime.charset) return mime.charset
 
  // default text/* to utf-8
  if (/^text\//.test(type)) return 'UTF-8'
 
  return false
}
 
// backwards compatibility
exports.charsets = {
  lookup: exports.charset
}
 
// to do: maybe use set-type module or something
exports.contentType = function (type) {
  if (!type || typeof type !== "string") return false
  if (!~type.indexOf('/')) type = exports.lookup(type)
  if (!type) return false
  if (!~type.indexOf('charset')) {
    var charset = exports.charset(type)
    if (charset) type += '; charset=' + charset.toLowerCase()
  }
  return type
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/type-is/node_modules/mime-types/node_modules/mime-db/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13                    1    
/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = require('./db.json')
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/utils-merge/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/utils-merge/

Statements: 20% (1 / 5)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 20% (1 / 5)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/utils-merge/
File Statements Branches Functions Lines
index.js 20% (1 / 5) 0% (0 / 4) 0% (0 / 1) 20% (1 / 5)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/utils-merge/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/utils-merge/index.js

Statements: 20% (1 / 5)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 20% (1 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25                              1                  
/**
 * Merge object b with object a.
 *
 *     var a = { foo: 'bar' }
 *       , b = { bar: 'baz' };
 *
 *     merge(a, b);
 *     // => { foo: 'bar', bar: 'baz' }
 *
 * @param {Object} a
 * @param {Object} b
 * @return {Object}
 * @api public
 */
 
exports = module.exports = function(a, b){
  if (a && b) {
    for (var key in b) {
      a[key] = b[key];
    }
  }
  return a;
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/vary/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/vary/

Statements: 19.35% (6 / 31)      Branches: 0% (0 / 27)      Functions: 0% (0 / 3)      Lines: 19.35% (6 / 31)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/express/node_modules/vary/
File Statements Branches Functions Lines
index.js 19.35% (6 / 31) 0% (0 / 27) 0% (0 / 3) 19.35% (6 / 31)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/vary/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/express/node_modules/vary/index.js

Statements: 19.35% (6 / 31)      Branches: 0% (0 / 27)      Functions: 0% (0 / 3)      Lines: 19.35% (6 / 31)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114                    1 1           1                     1                                                                                                                 1                       1                                
/*!
 * vary
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = vary;
module.exports.append = append;
 
/**
 * Variables.
 */
 
var separators = /[\(\)<>@,;:\\"\/\[\]\?=\{\}\u0020\u0009]/;
 
/**
 * Append a field to a vary header.
 *
 * @param {String} header
 * @param {String|Array} field
 * @return {String}
 * @api public
 */
 
function append(header, field) {
  if (typeof header !== 'string') {
    throw new TypeError('header argument is required');
  }
 
  if (!field) {
    throw new TypeError('field argument is required');
  }
 
  // get fields array
  var fields = !Array.isArray(field)
    ? parse(String(field))
    : field;
 
  // assert on invalid fields
  for (var i = 0; i < fields.length; i++) {
    if (separators.test(fields[i])) {
      throw new TypeError('field argument contains an invalid header');
    }
  }
 
  // existing, unspecified vary
  if (header === '*') {
    return header;
  }
 
  // enumerate current values
  var vals = parse(header.toLowerCase());
 
  // unspecified vary
  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
    return '*';
  }
 
  for (var i = 0; i < fields.length; i++) {
    field = fields[i].toLowerCase();
 
    // append value (case-preserving)
    if (vals.indexOf(field) === -1) {
      vals.push(field);
      header = header
        ? header + ', ' + fields[i]
        : fields[i];
    }
  }
 
  return header;
}
 
/**
 * Parse a vary header into an array.
 *
 * @param {String} header
 * @return {Array}
 * @api private
 */
 
function parse(header) {
  return header.trim().split(/ *, */);
}
 
/**
 * Mark that a request is varied on a header field.
 *
 * @param {Object} res
 * @param {String|Array} field
 * @api public
 */
 
function vary(res, field) {
  if (!res || !res.getHeader || !res.setHeader) {
    // quack quack
    throw new TypeError('res argument is required');
  }
 
  // get existing header
  var val = res.getHeader('Vary') || ''
  var header = Array.isArray(val)
    ? val.join(', ')
    : String(val);
 
  // set new header
  res.setHeader('Vary', append(header, field));
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/

Statements: 38.46% (25 / 65)      Branches: 11.76% (4 / 34)      Functions: 57.14% (4 / 7)      Lines: 38.46% (25 / 65)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/http-errors/
File Statements Branches Functions Lines
index.js 38.46% (25 / 65) 11.76% (4 / 34) 57.14% (4 / 7) 38.46% (25 / 65)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/index.js

Statements: 38.46% (25 / 65)      Branches: 11.76% (4 / 34)      Functions: 57.14% (4 / 7)      Lines: 38.46% (25 / 65)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122  1 1   1 40 94       1                                                                                                                 1 62     1 40 40   40 12                       12 12   12 12   12     28                       28 28   28 28   28       1    
 
var statuses = require('statuses');
var inherits = require('inherits');
 
function toIdentifier(str) {
  return str.split(' ').map(function (token) {
    return token.slice(0, 1).toUpperCase() + token.slice(1)
  }).join('').replace(/[^ _0-9a-z]/gi, '')
}
 
exports = module.exports = function httpError() {
  // so much arity going on ~_~
  var err;
  var msg;
  var status = 500;
  var props = {};
  for (var i = 0; i < arguments.length; i++) {
    var arg = arguments[i];
    if (arg instanceof Error) {
      err = arg;
      status = err.status || err.statusCode || status;
      continue;
    }
    switch (typeof arg) {
      case 'string':
        msg = arg;
        break;
      case 'number':
        status = arg;
        break;
      case 'object':
        props = arg;
        break;
    }
  }
 
  if (typeof status !== 'number' || !statuses[status]) {
    status = 500
  }
 
  // constructor
  var HttpError = exports[status]
 
  if (!err) {
    // create error
    err = HttpError
      ? new HttpError(msg)
      : new Error(msg || statuses[status])
    Error.captureStackTrace(err, httpError)
  }
 
  if (!HttpError || !(err instanceof HttpError)) {
    // add properties to generic error
    err.expose = status < 500
    err.status = err.statusCode = status
  }
 
  for (var key in props) {
    if (key !== 'status' && key !== 'statusCode') {
      err[key] = props[key]
    }
  }
 
  return err;
};
 
// create generic error objects
var codes = statuses.codes.filter(function (num) {
  return num >= 400;
});
 
codes.forEach(function (code) {
  var name = toIdentifier(statuses[code])
  var className = name.match(/Error$/) ? name : name + 'Error'
 
  if (code >= 500) {
    var ServerError = function ServerError(msg) {
      var self = new Error(msg != null ? msg : statuses[code])
      Error.captureStackTrace(self, ServerError)
      self.__proto__ = ServerError.prototype
      Object.defineProperty(self, 'name', {
        enumerable: false,
        configurable: true,
        value: className,
        writable: true
      })
      return self
    }
    inherits(ServerError, Error);
    ServerError.prototype.status =
    ServerError.prototype.statusCode = code;
    ServerError.prototype.expose = false;
    exports[code] =
    exports[name] = ServerError
    return;
  }
 
  var ClientError = function ClientError(msg) {
    var self = new Error(msg != null ? msg : statuses[code])
    Error.captureStackTrace(self, ClientError)
    self.__proto__ = ClientError.prototype
    Object.defineProperty(self, 'name', {
      enumerable: false,
      configurable: true,
      value: className,
      writable: true
    })
    return self
  }
  inherits(ClientError, Error);
  ClientError.prototype.status =
  ClientError.prototype.statusCode = code;
  ClientError.prototype.expose = true;
  exports[code] =
  exports[name] = ClientError
  return;
});
 
// backwards-compatibility
exports["I'mateapot"] = exports.ImATeapot
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/inherits/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/inherits/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/inherits/
File Statements Branches Functions Lines
inherits.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/inherits/inherits.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/inherits/inherits.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('util').inherits
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/statuses/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/statuses/

Statements: 44.44% (12 / 27)      Branches: 0% (0 / 12)      Functions: 50% (1 / 2)      Lines: 50% (12 / 24)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/statuses/
File Statements Branches Functions Lines
index.js 44.44% (12 / 27) 0% (0 / 12) 50% (1 / 2) 50% (12 / 24)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/statuses/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/http-errors/node_modules/statuses/index.js

Statements: 44.44% (12 / 27)      Branches: 0% (0 / 12)      Functions: 50% (1 / 2)      Lines: 50% (12 / 24)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62  1   1     1 62 62 62 62 62       1                     1             1           1                                            
 
var codes = require('./codes.json');
 
module.exports = status;
 
// [Integer...]
status.codes = Object.keys(codes).map(function (code) {
  code = ~~code;
  var msg = codes[code];
  status[code] = msg;
  status[msg] = status[msg.toLowerCase()] = code;
  return code;
});
 
// status codes for redirects
status.redirect = {
  300: true,
  301: true,
  302: true,
  303: true,
  305: true,
  307: true,
  308: true,
};
 
// status codes for empty bodies
status.empty = {
  204: true,
  205: true,
  304: true,
};
 
// status codes for when you should retry the request
status.retry = {
  502: true,
  503: true,
  504: true,
};
 
function status(code) {
  if (typeof code === 'number') {
    if (!status[code]) throw new Error('invalid status code: ' + code);
    return code;
  }
 
  if (typeof code !== 'string') {
    throw new TypeError('code must be a number or string');
  }
 
  // '403'
  var n = parseInt(code, 10)
  if (!isNaN(n)) {
    if (!status[n]) throw new Error('invalid status code: ' + n);
    return n;
  }
 
  n = status[code.toLowerCase()];
  if (!n) throw new Error('invalid status message: "' + code + '"');
  return n;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/jju/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/jju/

Statements: 50% (6 / 12)      Branches: 100% (0 / 0)      Functions: 0% (0 / 6)      Lines: 50% (6 / 12)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/jju/
File Statements Branches Functions Lines
index.js 50% (6 / 12) 100% (0 / 0) 0% (0 / 6) 50% (6 / 12)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/jju/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/jju/index.js

Statements: 50% (6 / 12)      Branches: 100% (0 / 0)      Functions: 0% (0 / 6)      Lines: 50% (6 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  1       1       1       1       1       1                        
 
module.exports.__defineGetter__('parse', function() {
	return require('./lib/parse').parse
})
 
module.exports.__defineGetter__('stringify', function() {
	return require('./lib/stringify').stringify
})
 
module.exports.__defineGetter__('tokenize', function() {
	return require('./lib/parse').tokenize
})
 
module.exports.__defineGetter__('update', function() {
	return require('./lib/document').update
})
 
module.exports.__defineGetter__('analyze', function() {
	return require('./lib/analyze').analyze
})
 
module.exports.__defineGetter__('utils', function() {
	return require('./lib/utils')
})
 
/**package
{ "name": "jju",
  "version": "0.0.0",
  "dependencies": {"js-yaml": "*"},
  "scripts": {"postinstall": "js-yaml package.yaml > package.json ; npm install"}
}
**/
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/
File Statements Branches Functions Lines
index.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/index.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9      1     1    
'use strict';
 
 
var yaml = require('./lib/js-yaml.js');
 
 
module.exports = yaml;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/

Statements: 96.15% (25 / 26)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 96.15% (25 / 26)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/
File Statements Branches Functions Lines
js-yaml.js 96.15% (25 / 26) 100% (0 / 0) 50% (1 / 2) 96.15% (25 / 26)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml.js

Statements: 96.15% (25 / 26)      Branches: 100% (0 / 0)      Functions: 50% (1 / 2)      Lines: 96.15% (25 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41      1 1     1 4           1 1 1 1 1 1 1 1 1 1 1 1 1 1     1 1 1     1 1 1 1    
'use strict';
 
 
var loader = require('./js-yaml/loader');
var dumper = require('./js-yaml/dumper');
 
 
function deprecated(name) {
  return function () {
    throw new Error('Function ' + name + ' is deprecated and cannot be used.');
  };
}
 
 
module.exports.Type                = require('./js-yaml/type');
module.exports.Schema              = require('./js-yaml/schema');
module.exports.FAILSAFE_SCHEMA     = require('./js-yaml/schema/failsafe');
module.exports.JSON_SCHEMA         = require('./js-yaml/schema/json');
module.exports.CORE_SCHEMA         = require('./js-yaml/schema/core');
module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');
module.exports.load                = loader.load;
module.exports.loadAll             = loader.loadAll;
module.exports.safeLoad            = loader.safeLoad;
module.exports.safeLoadAll         = loader.safeLoadAll;
module.exports.dump                = dumper.dump;
module.exports.safeDump            = dumper.safeDump;
module.exports.YAMLException       = require('./js-yaml/exception');
 
// Deprecared schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.SAFE_SCHEMA    = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');
 
// Deprecated functions from JS-YAML 1.x.x
module.exports.scan           = deprecated('scan');
module.exports.parse          = deprecated('parse');
module.exports.compose        = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/

Statements: 39.21% (545 / 1390)      Branches: 29.57% (293 / 991)      Functions: 45.74% (43 / 94)      Lines: 39.52% (545 / 1379)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/
File Statements Branches Functions Lines
common.js 61.29% (19 / 31) 8.33% (1 / 12) 33.33% (2 / 6) 61.29% (19 / 31)
dumper.js 16.78% (73 / 435) 0% (0 / 324) 0% (0 / 25) 16.78% (73 / 435)
exception.js 25% (3 / 12) 0% (0 / 6) 0% (0 / 2) 25% (3 / 12)
loader.js 49.18% (388 / 789) 44.88% (263 / 586) 69.23% (27 / 39) 49.62% (388 / 782)
mark.js 11.9% (5 / 42) 0% (0 / 20) 0% (0 / 3) 11.9% (5 / 42)
schema.js 61.54% (32 / 52) 47.37% (9 / 19) 75% (9 / 12) 64% (32 / 50)
type.js 86.21% (25 / 29) 83.33% (20 / 24) 71.43% (5 / 7) 92.59% (25 / 27)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/common.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/common.js

Statements: 61.29% (19 / 31)      Branches: 8.33% (1 / 12)      Functions: 33.33% (2 / 6)      Lines: 61.29% (19 / 31)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63      1         1         1                   1 1   1                 1       1 13   13 13     13       1         1 1 1 1 1 1    
'use strict';
 
 
function isNothing(subject) {
  return (typeof subject === 'undefined') || (null === subject);
}
 
 
function isObject(subject) {
  return (typeof subject === 'object') && (null !== subject);
}
 
 
function toArray(sequence) {
  if (Array.isArray(sequence)) {
    return sequence;
  } else if (isNothing(sequence)) {
    return [];
  }
  return [ sequence ];
}
 
 
function extend(target, source) {
  var index, length, key, sourceKeys;
 
  Iif (source) {
    sourceKeys = Object.keys(source);
 
    for (index = 0, length = sourceKeys.length; index < length; index += 1) {
      key = sourceKeys[index];
      target[key] = source[key];
    }
  }
 
  return target;
}
 
 
function repeat(string, count) {
  var result = '', cycle;
 
  for (cycle = 0; cycle < count; cycle += 1) {
    result += string;
  }
 
  return result;
}
 
 
function isNegativeZero(number) {
  return (0 === number) && (Number.NEGATIVE_INFINITY === 1 / number);
}
 
 
module.exports.isNothing      = isNothing;
module.exports.isObject       = isObject;
module.exports.toArray        = toArray;
module.exports.repeat         = repeat;
module.exports.isNegativeZero = isNegativeZero;
module.exports.extend         = extend;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/dumper.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/dumper.js

Statements: 16.78% (73 / 435)      Branches: 0% (0 / 324)      Functions: 0% (0 / 25)      Lines: 16.78% (73 / 435)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844        1 1 1 1   1 1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1   1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   1         1                                                           1                                         1                                   1                                                   1       1                           1           1                             1                     1           1                                                                                                                                                                                                                                                                                                                                                               1                                                                   1                                                                                                             1                                               1               1                                       1                                       1                                                                                       1                                                                                                                                                   1                                                                           1                                                                                                                                                       1                           1                                                           1                         1       1 1    
'use strict';
 
/*eslint-disable no-use-before-define*/
 
var common              = require('./common');
var YAMLException       = require('./exception');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
 
var _toString       = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
 
var CHAR_TAB                  = 0x09; /* Tab */
var CHAR_LINE_FEED            = 0x0A; /* LF */
var CHAR_CARRIAGE_RETURN      = 0x0D; /* CR */
var CHAR_SPACE                = 0x20; /* Space */
var CHAR_EXCLAMATION          = 0x21; /* ! */
var CHAR_DOUBLE_QUOTE         = 0x22; /* " */
var CHAR_SHARP                = 0x23; /* # */
var CHAR_PERCENT              = 0x25; /* % */
var CHAR_AMPERSAND            = 0x26; /* & */
var CHAR_SINGLE_QUOTE         = 0x27; /* ' */
var CHAR_ASTERISK             = 0x2A; /* * */
var CHAR_COMMA                = 0x2C; /* , */
var CHAR_MINUS                = 0x2D; /* - */
var CHAR_COLON                = 0x3A; /* : */
var CHAR_GREATER_THAN         = 0x3E; /* > */
var CHAR_QUESTION             = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT        = 0x40; /* @ */
var CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */
var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
var CHAR_GRAVE_ACCENT         = 0x60; /* ` */
var CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */
var CHAR_VERTICAL_LINE        = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */
 
var ESCAPE_SEQUENCES = {};
 
ESCAPE_SEQUENCES[0x00]   = '\\0';
ESCAPE_SEQUENCES[0x07]   = '\\a';
ESCAPE_SEQUENCES[0x08]   = '\\b';
ESCAPE_SEQUENCES[0x09]   = '\\t';
ESCAPE_SEQUENCES[0x0A]   = '\\n';
ESCAPE_SEQUENCES[0x0B]   = '\\v';
ESCAPE_SEQUENCES[0x0C]   = '\\f';
ESCAPE_SEQUENCES[0x0D]   = '\\r';
ESCAPE_SEQUENCES[0x1B]   = '\\e';
ESCAPE_SEQUENCES[0x22]   = '\\"';
ESCAPE_SEQUENCES[0x5C]   = '\\\\';
ESCAPE_SEQUENCES[0x85]   = '\\N';
ESCAPE_SEQUENCES[0xA0]   = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P';
 
var DEPRECATED_BOOLEANS_SYNTAX = [
  'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
  'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];
 
function compileStyleMap(schema, map) {
  var result, keys, index, length, tag, style, type;
 
  if (null === map) {
    return {};
  }
 
  result = {};
  keys = Object.keys(map);
 
  for (index = 0, length = keys.length; index < length; index += 1) {
    tag = keys[index];
    style = String(map[tag]);
 
    if ('!!' === tag.slice(0, 2)) {
      tag = 'tag:yaml.org,2002:' + tag.slice(2);
    }
 
    type = schema.compiledTypeMap[tag];
 
    if (type && _hasOwnProperty.call(type.styleAliases, style)) {
      style = type.styleAliases[style];
    }
 
    result[tag] = style;
  }
 
  return result;
}
 
function encodeHex(character) {
  var string, handle, length;
 
  string = character.toString(16).toUpperCase();
 
  if (character <= 0xFF) {
    handle = 'x';
    length = 2;
  } else if (character <= 0xFFFF) {
    handle = 'u';
    length = 4;
  } else if (character <= 0xFFFFFFFF) {
    handle = 'U';
    length = 8;
  } else {
    throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
  }
 
  return '\\' + handle + common.repeat('0', length - string.length) + string;
}
 
function State(options) {
  this.schema      = options['schema'] || DEFAULT_FULL_SCHEMA;
  this.indent      = Math.max(1, (options['indent'] || 2));
  this.skipInvalid = options['skipInvalid'] || false;
  this.flowLevel   = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
  this.styleMap    = compileStyleMap(this.schema, options['styles'] || null);
  this.sortKeys    = options['sortKeys'] || false;
 
  this.implicitTypes = this.schema.compiledImplicit;
  this.explicitTypes = this.schema.compiledExplicit;
 
  this.tag = null;
  this.result = '';
 
  this.duplicates = [];
  this.usedDuplicates = null;
}
 
function indentString(string, spaces) {
  var ind = common.repeat(' ', spaces),
      position = 0,
      next = -1,
      result = '',
      line,
      length = string.length;
 
  while (position < length) {
    next = string.indexOf('\n', position);
    if (next === -1) {
      line = string.slice(position);
      position = length;
    } else {
      line = string.slice(position, next + 1);
      position = next + 1;
    }
    if (line.length && line !== '\n') {
      result += ind;
    }
    result += line;
  }
 
  return result;
}
 
function generateNextLine(state, level) {
  return '\n' + common.repeat(' ', state.indent * level);
}
 
function testImplicitResolving(state, str) {
  var index, length, type;
 
  for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
    type = state.implicitTypes[index];
 
    if (type.resolve(str)) {
      return true;
    }
  }
 
  return false;
}
 
function StringBuilder(source) {
  this.source = source;
  this.result = '';
  this.checkpoint = 0;
}
 
StringBuilder.prototype.takeUpTo = function (position) {
  var er;
 
  if (position < this.checkpoint) {
    er = new Error('position should be > checkpoint');
    er.position = position;
    er.checkpoint = this.checkpoint;
    throw er;
  }
 
  this.result += this.source.slice(this.checkpoint, position);
  this.checkpoint = position;
  return this;
};
 
StringBuilder.prototype.escapeChar = function () {
  var character, esc;
 
  character = this.source.charCodeAt(this.checkpoint);
  esc = ESCAPE_SEQUENCES[character] || encodeHex(character);
  this.result += esc;
  this.checkpoint += 1;
 
  return this;
};
 
StringBuilder.prototype.finish = function () {
  if (this.source.length > this.checkpoint) {
    this.takeUpTo(this.source.length);
  }
};
 
function writeScalar(state, object, level) {
  var simple, first, spaceWrap, folded, literal, single, double,
      sawLineFeed, linePosition, longestLine, indent, max, character,
      position, escapeSeq, hexEsc, previous, lineLength, modifier,
      trailingLineBreaks, result;
 
  if (0 === object.length) {
    state.dump = "''";
    return;
  }
 
  if (-1 !== DEPRECATED_BOOLEANS_SYNTAX.indexOf(object)) {
    state.dump = "'" + object + "'";
    return;
  }
 
  simple = true;
  first = object.length ? object.charCodeAt(0) : 0;
  spaceWrap = (CHAR_SPACE === first ||
               CHAR_SPACE === object.charCodeAt(object.length - 1));
 
  // Simplified check for restricted first characters
  // http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29
  if (CHAR_MINUS         === first ||
      CHAR_QUESTION      === first ||
      CHAR_COMMERCIAL_AT === first ||
      CHAR_GRAVE_ACCENT  === first) {
    simple = false;
  }
 
  // can only use > and | if not wrapped in spaces.
  if (spaceWrap) {
    simple = false;
    folded = false;
    literal = false;
  } else {
    folded = true;
    literal = true;
  }
 
  single = true;
  double = new StringBuilder(object);
 
  sawLineFeed = false;
  linePosition = 0;
  longestLine = 0;
 
  indent = state.indent * level;
  max = 80;
  if (indent < 40) {
    max -= indent;
  } else {
    max = 40;
  }
 
  for (position = 0; position < object.length; position++) {
    character = object.charCodeAt(position);
    if (simple) {
      // Characters that can never appear in the simple scalar
      if (!simpleChar(character)) {
        simple = false;
      } else {
        // Still simple.  If we make it all the way through like
        // this, then we can just dump the string as-is.
        continue;
      }
    }
 
    if (single && character === CHAR_SINGLE_QUOTE) {
      single = false;
    }
 
    escapeSeq = ESCAPE_SEQUENCES[character];
    hexEsc = needsHexEscape(character);
 
    if (!escapeSeq && !hexEsc) {
      continue;
    }
 
    if (character !== CHAR_LINE_FEED &&
        character !== CHAR_DOUBLE_QUOTE &&
        character !== CHAR_SINGLE_QUOTE) {
      folded = false;
      literal = false;
    } else if (character === CHAR_LINE_FEED) {
      sawLineFeed = true;
      single = false;
      if (position > 0) {
        previous = object.charCodeAt(position - 1);
        if (previous === CHAR_SPACE) {
          literal = false;
          folded = false;
        }
      }
      if (folded) {
        lineLength = position - linePosition;
        linePosition = position;
        if (lineLength > longestLine) {
          longestLine = lineLength;
        }
      }
    }
 
    if (character !== CHAR_DOUBLE_QUOTE) {
      single = false;
    }
 
    double.takeUpTo(position);
    double.escapeChar();
  }
 
  if (simple && testImplicitResolving(state, object)) {
    simple = false;
  }
 
  modifier = '';
  if (folded || literal) {
    trailingLineBreaks = 0;
    if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) {
      trailingLineBreaks += 1;
      if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) {
        trailingLineBreaks += 1;
      }
    }
 
    if (trailingLineBreaks === 0) {
      modifier = '-';
    } else if (trailingLineBreaks === 2) {
      modifier = '+';
    }
  }
 
  if (literal && longestLine < max) {
    folded = false;
  }
 
  // If it's literally one line, then don't bother with the literal.
  // We may still want to do a fold, though, if it's a super long line.
  if (!sawLineFeed) {
    literal = false;
  }
 
  if (simple) {
    state.dump = object;
  } else if (single) {
    state.dump = '\'' + object + '\'';
  } else if (folded) {
    result = fold(object, max);
    state.dump = '>' + modifier + '\n' + indentString(result, indent);
  } else if (literal) {
    if (!modifier) {
      object = object.replace(/\n$/, '');
    }
    state.dump = '|' + modifier + '\n' + indentString(object, indent);
  } else if (double) {
    double.finish();
    state.dump = '"' + double.result + '"';
  } else {
    throw new Error('Failed to dump scalar value');
  }
 
  return;
}
 
// The `trailing` var is a regexp match of any trailing `\n` characters.
//
// There are three cases we care about:
//
// 1. One trailing `\n` on the string.  Just use `|` or `>`.
//    This is the assumed default. (trailing = null)
// 2. No trailing `\n` on the string.  Use `|-` or `>-` to "chomp" the end.
// 3. More than one trailing `\n` on the string.  Use `|+` or `>+`.
//
// In the case of `>+`, these line breaks are *not* doubled (like the line
// breaks within the string), so it's important to only end with the exact
// same number as we started.
function fold(object, max) {
  var result = '',
      position = 0,
      length = object.length,
      trailing = /\n+$/.exec(object),
      newLine;
 
  if (trailing) {
    length = trailing.index + 1;
  }
 
  while (position < length) {
    newLine = object.indexOf('\n', position);
    if (newLine > length || newLine === -1) {
      if (result) {
        result += '\n\n';
      }
      result += foldLine(object.slice(position, length), max);
      position = length;
    } else {
      if (result) {
        result += '\n\n';
      }
      result += foldLine(object.slice(position, newLine), max);
      position = newLine + 1;
    }
  }
  if (trailing && trailing[0] !== '\n') {
    result += trailing[0];
  }
 
  return result;
}
 
function foldLine(line, max) {
  if (line === '') {
    return line;
  }
 
  var foldRe = /[^\s] [^\s]/g,
      result = '',
      prevMatch = 0,
      foldStart = 0,
      match = foldRe.exec(line),
      index,
      foldEnd,
      folded;
 
  while (match) {
    index = match.index;
 
    // when we cross the max len, if the previous match would've
    // been ok, use that one, and carry on.  If there was no previous
    // match on this fold section, then just have a long line.
    if (index - foldStart > max) {
      if (prevMatch !== foldStart) {
        foldEnd = prevMatch;
      } else {
        foldEnd = index;
      }
 
      if (result) {
        result += '\n';
      }
      folded = line.slice(foldStart, foldEnd);
      result += folded;
      foldStart = foldEnd + 1;
    }
    prevMatch = index + 1;
    match = foldRe.exec(line);
  }
 
  if (result) {
    result += '\n';
  }
 
  // if we end up with one last word at the end, then the last bit might
  // be slightly bigger than we wanted, because we exited out of the loop.
  if (foldStart !== prevMatch && line.length - foldStart > max) {
    result += line.slice(foldStart, prevMatch) + '\n' +
              line.slice(prevMatch + 1);
  } else {
    result += line.slice(foldStart);
  }
 
  return result;
}
 
// Returns true if character can be found in a simple scalar
function simpleChar(character) {
  return CHAR_TAB                  !== character &&
         CHAR_LINE_FEED            !== character &&
         CHAR_CARRIAGE_RETURN      !== character &&
         CHAR_COMMA                !== character &&
         CHAR_LEFT_SQUARE_BRACKET  !== character &&
         CHAR_RIGHT_SQUARE_BRACKET !== character &&
         CHAR_LEFT_CURLY_BRACKET   !== character &&
         CHAR_RIGHT_CURLY_BRACKET  !== character &&
         CHAR_SHARP                !== character &&
         CHAR_AMPERSAND            !== character &&
         CHAR_ASTERISK             !== character &&
         CHAR_EXCLAMATION          !== character &&
         CHAR_VERTICAL_LINE        !== character &&
         CHAR_GREATER_THAN         !== character &&
         CHAR_SINGLE_QUOTE         !== character &&
         CHAR_DOUBLE_QUOTE         !== character &&
         CHAR_PERCENT              !== character &&
         CHAR_COLON                !== character &&
         !ESCAPE_SEQUENCES[character]            &&
         !needsHexEscape(character);
}
 
// Returns true if the character code needs to be escaped.
function needsHexEscape(character) {
  return !((0x00020 <= character && character <= 0x00007E) ||
           (0x00085 === character)                         ||
           (0x000A0 <= character && character <= 0x00D7FF) ||
           (0x0E000 <= character && character <= 0x00FFFD) ||
           (0x10000 <= character && character <= 0x10FFFF));
}
 
function writeFlowSequence(state, level, object) {
  var _result = '',
      _tag    = state.tag,
      index,
      length;
 
  for (index = 0, length = object.length; index < length; index += 1) {
    // Write only valid elements.
    if (writeNode(state, level, object[index], false, false)) {
      if (0 !== index) {
        _result += ', ';
      }
      _result += state.dump;
    }
  }
 
  state.tag = _tag;
  state.dump = '[' + _result + ']';
}
 
function writeBlockSequence(state, level, object, compact) {
  var _result = '',
      _tag    = state.tag,
      index,
      length;
 
  for (index = 0, length = object.length; index < length; index += 1) {
    // Write only valid elements.
    if (writeNode(state, level + 1, object[index], true, true)) {
      if (!compact || 0 !== index) {
        _result += generateNextLine(state, level);
      }
      _result += '- ' + state.dump;
    }
  }
 
  state.tag = _tag;
  state.dump = _result || '[]'; // Empty sequence if no valid values.
}
 
function writeFlowMapping(state, level, object) {
  var _result       = '',
      _tag          = state.tag,
      objectKeyList = Object.keys(object),
      index,
      length,
      objectKey,
      objectValue,
      pairBuffer;
 
  for (index = 0, length = objectKeyList.length; index < length; index += 1) {
    pairBuffer = '';
 
    if (0 !== index) {
      pairBuffer += ', ';
    }
 
    objectKey = objectKeyList[index];
    objectValue = object[objectKey];
 
    if (!writeNode(state, level, objectKey, false, false)) {
      continue; // Skip this pair because of invalid key;
    }
 
    if (state.dump.length > 1024) {
      pairBuffer += '? ';
    }
 
    pairBuffer += state.dump + ': ';
 
    if (!writeNode(state, level, objectValue, false, false)) {
      continue; // Skip this pair because of invalid value.
    }
 
    pairBuffer += state.dump;
 
    // Both key and value are valid.
    _result += pairBuffer;
  }
 
  state.tag = _tag;
  state.dump = '{' + _result + '}';
}
 
function writeBlockMapping(state, level, object, compact) {
  var _result       = '',
      _tag          = state.tag,
      objectKeyList = Object.keys(object),
      index,
      length,
      objectKey,
      objectValue,
      explicitPair,
      pairBuffer;
 
  // Allow sorting keys so that the output file is deterministic
  if (state.sortKeys === true) {
    // Default sorting
    objectKeyList.sort();
  } else if (typeof state.sortKeys === 'function') {
    // Custom sort function
    objectKeyList.sort(state.sortKeys);
  } else if (state.sortKeys) {
    // Something is wrong
    throw new YAMLException('sortKeys must be a boolean or a function');
  }
 
  for (index = 0, length = objectKeyList.length; index < length; index += 1) {
    pairBuffer = '';
 
    if (!compact || 0 !== index) {
      pairBuffer += generateNextLine(state, level);
    }
 
    objectKey = objectKeyList[index];
    objectValue = object[objectKey];
 
    if (!writeNode(state, level + 1, objectKey, true, true)) {
      continue; // Skip this pair because of invalid key.
    }
 
    explicitPair = (null !== state.tag && '?' !== state.tag) ||
                   (state.dump && state.dump.length > 1024);
 
    if (explicitPair) {
      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
        pairBuffer += '?';
      } else {
        pairBuffer += '? ';
      }
    }
 
    pairBuffer += state.dump;
 
    if (explicitPair) {
      pairBuffer += generateNextLine(state, level);
    }
 
    if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
      continue; // Skip this pair because of invalid value.
    }
 
    if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
      pairBuffer += ':';
    } else {
      pairBuffer += ': ';
    }
 
    pairBuffer += state.dump;
 
    // Both key and value are valid.
    _result += pairBuffer;
  }
 
  state.tag = _tag;
  state.dump = _result || '{}'; // Empty mapping if no valid pairs.
}
 
function detectType(state, object, explicit) {
  var _result, typeList, index, length, type, style;
 
  typeList = explicit ? state.explicitTypes : state.implicitTypes;
 
  for (index = 0, length = typeList.length; index < length; index += 1) {
    type = typeList[index];
 
    if ((type.instanceOf  || type.predicate) &&
        (!type.instanceOf || (('object' === typeof object) && (object instanceof type.instanceOf))) &&
        (!type.predicate  || type.predicate(object))) {
 
      state.tag = explicit ? type.tag : '?';
 
      if (type.represent) {
        style = state.styleMap[type.tag] || type.defaultStyle;
 
        if ('[object Function]' === _toString.call(type.represent)) {
          _result = type.represent(object, style);
        } else if (_hasOwnProperty.call(type.represent, style)) {
          _result = type.represent[style](object, style);
        } else {
          throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
        }
 
        state.dump = _result;
      }
 
      return true;
    }
  }
 
  return false;
}
 
// Serializes `object` and writes it to global `result`.
// Returns true on success, or false on invalid object.
//
function writeNode(state, level, object, block, compact) {
  state.tag = null;
  state.dump = object;
 
  if (!detectType(state, object, false)) {
    detectType(state, object, true);
  }
 
  var type = _toString.call(state.dump);
 
  if (block) {
    block = (0 > state.flowLevel || state.flowLevel > level);
  }
 
  if ((null !== state.tag && '?' !== state.tag) || (2 !== state.indent && level > 0)) {
    compact = false;
  }
 
  var objectOrArray = '[object Object]' === type || '[object Array]' === type,
      duplicateIndex,
      duplicate;
 
  if (objectOrArray) {
    duplicateIndex = state.duplicates.indexOf(object);
    duplicate = duplicateIndex !== -1;
  }
 
  if (duplicate && state.usedDuplicates[duplicateIndex]) {
    state.dump = '*ref_' + duplicateIndex;
  } else {
    if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
      state.usedDuplicates[duplicateIndex] = true;
    }
    if ('[object Object]' === type) {
      if (block && (0 !== Object.keys(state.dump).length)) {
        writeBlockMapping(state, level, state.dump, compact);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump;
        }
      } else {
        writeFlowMapping(state, level, state.dump);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
        }
      }
    } else if ('[object Array]' === type) {
      if (block && (0 !== state.dump.length)) {
        writeBlockSequence(state, level, state.dump, compact);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump;
        }
      } else {
        writeFlowSequence(state, level, state.dump);
        if (duplicate) {
          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
        }
      }
    } else if ('[object String]' === type) {
      if ('?' !== state.tag) {
        writeScalar(state, state.dump, level);
      }
    } else {
      if (state.skipInvalid) {
        return false;
      }
      throw new YAMLException('unacceptable kind of an object to dump ' + type);
    }
 
    if (null !== state.tag && '?' !== state.tag) {
      state.dump = '!<' + state.tag + '> ' + state.dump;
    }
  }
 
  return true;
}
 
function getDuplicateReferences(object, state) {
  var objects = [],
      duplicatesIndexes = [],
      index,
      length;
 
  inspectNode(object, objects, duplicatesIndexes);
 
  for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
    state.duplicates.push(objects[duplicatesIndexes[index]]);
  }
  state.usedDuplicates = new Array(length);
}
 
function inspectNode(object, objects, duplicatesIndexes) {
  var type = _toString.call(object),
      objectKeyList,
      index,
      length;
 
  if (null !== object && 'object' === typeof object) {
    index = objects.indexOf(object);
    if (-1 !== index) {
      if (-1 === duplicatesIndexes.indexOf(index)) {
        duplicatesIndexes.push(index);
      }
    } else {
      objects.push(object);
 
      if (Array.isArray(object)) {
        for (index = 0, length = object.length; index < length; index += 1) {
          inspectNode(object[index], objects, duplicatesIndexes);
        }
      } else {
        objectKeyList = Object.keys(object);
 
        for (index = 0, length = objectKeyList.length; index < length; index += 1) {
          inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
        }
      }
    }
  }
}
 
function dump(input, options) {
  options = options || {};
 
  var state = new State(options);
 
  getDuplicateReferences(input, state);
 
  if (writeNode(state, 0, input, true, true)) {
    return state.dump + '\n';
  }
  return '';
}
 
function safeDump(input, options) {
  return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
 
module.exports.dump     = dump;
module.exports.safeDump = safeDump;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/exception.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/exception.js

Statements: 25% (3 / 12)      Branches: 0% (0 / 6)      Functions: 0% (0 / 2)      Lines: 25% (3 / 12)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27      1               1                         1    
'use strict';
 
 
function YAMLException(reason, mark) {
  this.name    = 'YAMLException';
  this.reason  = reason;
  this.mark    = mark;
  this.message = this.toString(false);
}
 
 
YAMLException.prototype.toString = function toString(compact) {
  var result;
 
  result = 'JS-YAML: ' + (this.reason || '(unknown reason)');
 
  if (!compact && this.mark) {
    result += ' ' + this.mark.toString();
  }
 
  return result;
};
 
 
module.exports = YAMLException;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/loader.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/loader.js

Statements: 49.18% (388 / 789)      Branches: 44.88% (263 / 586)      Functions: 69.23% (27 / 39)      Lines: 49.62% (388 / 782)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588        1 1 1 1 1     1     1 1 1 1     1 1 1     1 1 1 1 1     1 2295     1 1545     1 245           1 95             1                                 1             1 1       1     1 512                                       1                   1 1 1 256 256       1 1   1 1 1 1   1 1   1 1 1 1 1   1                             1           1       1                     1                                                                                                                             1 149   149 149   149 40     472 472             149       1                                   1 70   70   70       70                 70     70     1 168   168   168 168                   168 168     1 182     182 330 67     330 22 610       330 152   152 152 152   152 186 186     178       182       182     1 17     17       17                         17     1                 1 95                       95   95                               95                 95 95 95 95   95 1165 73   73   70     1092             1092       1092 25 25 25 25   25         25 25 25 25 25       1070             1070 1045     1070     95   95 95               1 135     135   135 95     40 40 40 40   40 512 40 40   40       40     472         472       472 472             1 95             95   95 95                                                                                                                                       1 136                             136   136       136         136                                                                                                                                                         1 59                   59   59 1 58     58     1 1   1 1   1             1                     1       1                   1 16 16   16   16   56 56     16 1     16 1 1       15     1   1 1 1         1       14                                               14   13         14 14 14   14 371     14     1     1 19               19       19   19   25 18     7   7       7 7   7               7 7 7 7   7   7   7 1       19 1 1 1 1 1   18     1 18                         18       18   18 77 77           77                                                     77   77 77   77       77 70   70       70         70 70 70 70 70   7       7 7 7                                     70 70 70     70       70 70 70     70 70     70   70 10                 11         11 11 11 11 11     11     1 155             155   155 155                                                                                                                                                                         1 155     155   155 155                                           1 95         95   95 95                                                 1 155                         155 155 155 155   155       155 70 11   11 11                 155 155                                   155 78     155 155 77   78     155   155 155       19   136     41   95             95 95   95 95       136                     155 95 95     566           566 1 1 1     1                                             155     1 1             1 1 1 1   1 1   1   1 1                                                                                                         1   1             1       1 1   1         1   1                 1     1         1 1 1   1     1           1         1   1         1   1         1 1     1       1                 1 1   1     1 1           1         1 1       1 1 1 1    
'use strict';
 
/*eslint-disable max-len,no-use-before-define*/
 
var common              = require('./common');
var YAMLException       = require('./exception');
var Mark                = require('./mark');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
 
 
var _hasOwnProperty = Object.prototype.hasOwnProperty;
 
 
var CONTEXT_FLOW_IN   = 1;
var CONTEXT_FLOW_OUT  = 2;
var CONTEXT_BLOCK_IN  = 3;
var CONTEXT_BLOCK_OUT = 4;
 
 
var CHOMPING_CLIP  = 1;
var CHOMPING_STRIP = 2;
var CHOMPING_KEEP  = 3;
 
 
var PATTERN_NON_PRINTABLE         = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
var PATTERN_FLOW_INDICATORS       = /[,\[\]\{\}]/;
var PATTERN_TAG_HANDLE            = /^(?:!|!!|![a-z\-]+!)$/i;
var PATTERN_TAG_URI               = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
 
 
function is_EOL(c) {
  return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
}
 
function is_WHITE_SPACE(c) {
  return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
}
 
function is_WS_OR_EOL(c) {
  return (c === 0x09/* Tab */) ||
         (c === 0x20/* Space */) ||
         (c === 0x0A/* LF */) ||
         (c === 0x0D/* CR */);
}
 
function is_FLOW_INDICATOR(c) {
  return 0x2C/* , */ === c ||
         0x5B/* [ */ === c ||
         0x5D/* ] */ === c ||
         0x7B/* { */ === c ||
         0x7D/* } */ === c;
}
 
function fromHexCode(c) {
  var lc;
 
  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
    return c - 0x30;
  }
 
  /*eslint-disable no-bitwise*/
  lc = c | 0x20;
 
  if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
    return lc - 0x61 + 10;
  }
 
  return -1;
}
 
function escapedHexLen(c) {
  if (c === 0x78/* x */) { return 2; }
  if (c === 0x75/* u */) { return 4; }
  if (c === 0x55/* U */) { return 8; }
  return 0;
}
 
function fromDecimalCode(c) {
  Iif ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
    return c - 0x30;
  }
 
  return -1;
}
 
function simpleEscapeSequence(c) {
  return (c === 0x30/* 0 */) ? '\x00' :
        (c === 0x61/* a */) ? '\x07' :
        (c === 0x62/* b */) ? '\x08' :
        (c === 0x74/* t */) ? '\x09' :
        (c === 0x09/* Tab */) ? '\x09' :
        (c === 0x6E/* n */) ? '\x0A' :
        (c === 0x76/* v */) ? '\x0B' :
        (c === 0x66/* f */) ? '\x0C' :
        (c === 0x72/* r */) ? '\x0D' :
        (c === 0x65/* e */) ? '\x1B' :
        (c === 0x20/* Space */) ? ' ' :
        (c === 0x22/* " */) ? '\x22' :
        (c === 0x2F/* / */) ? '/' :
        (c === 0x5C/* \ */) ? '\x5C' :
        (c === 0x4E/* N */) ? '\x85' :
        (c === 0x5F/* _ */) ? '\xA0' :
        (c === 0x4C/* L */) ? '\u2028' :
        (c === 0x50/* P */) ? '\u2029' : '';
}
 
function charFromCodepoint(c) {
  if (c <= 0xFFFF) {
    return String.fromCharCode(c);
  }
  // Encode UTF-16 surrogate pair
  // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
  return String.fromCharCode(((c - 0x010000) >> 10) + 0xD800,
                             ((c - 0x010000) & 0x03FF) + 0xDC00);
}
 
var simpleEscapeCheck = new Array(256); // integer, for fast access
var simpleEscapeMap = new Array(256);
for (var i = 0; i < 256; i++) {
  simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
  simpleEscapeMap[i] = simpleEscapeSequence(i);
}
 
 
function State(input, options) {
  this.input = input;
 
  this.filename  = options['filename']  || null;
  this.schema    = options['schema']    || DEFAULT_FULL_SCHEMA;
  this.onWarning = options['onWarning'] || null;
  this.legacy    = options['legacy']    || false;
 
  this.implicitTypes = this.schema.compiledImplicit;
  this.typeMap       = this.schema.compiledTypeMap;
 
  this.length     = input.length;
  this.position   = 0;
  this.line       = 0;
  this.lineStart  = 0;
  this.lineIndent = 0;
 
  this.documents = [];
 
  /*
  this.version;
  this.checkLineBreaks;
  this.tagMap;
  this.anchorMap;
  this.tag;
  this.anchor;
  this.kind;
  this.result;*/
 
}
 
 
function generateError(state, message) {
  return new YAMLException(
    message,
    new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));
}
 
function throwError(state, message) {
  throw generateError(state, message);
}
 
function throwWarning(state, message) {
  var error = generateError(state, message);
 
  if (state.onWarning) {
    state.onWarning.call(null, error);
  } else {
    throw error;
  }
}
 
 
var directiveHandlers = {
 
  YAML: function handleYamlDirective(state, name, args) {
 
      var match, major, minor;
 
      if (null !== state.version) {
        throwError(state, 'duplication of %YAML directive');
      }
 
      if (1 !== args.length) {
        throwError(state, 'YAML directive accepts exactly one argument');
      }
 
      match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
 
      if (null === match) {
        throwError(state, 'ill-formed argument of the YAML directive');
      }
 
      major = parseInt(match[1], 10);
      minor = parseInt(match[2], 10);
 
      if (1 !== major) {
        throwError(state, 'unacceptable YAML version of the document');
      }
 
      state.version = args[0];
      state.checkLineBreaks = (minor < 2);
 
      if (1 !== minor && 2 !== minor) {
        throwWarning(state, 'unsupported YAML version of the document');
      }
    },
 
  TAG: function handleTagDirective(state, name, args) {
 
      var handle, prefix;
 
      if (2 !== args.length) {
        throwError(state, 'TAG directive accepts exactly two arguments');
      }
 
      handle = args[0];
      prefix = args[1];
 
      if (!PATTERN_TAG_HANDLE.test(handle)) {
        throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
      }
 
      if (_hasOwnProperty.call(state.tagMap, handle)) {
        throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
      }
 
      if (!PATTERN_TAG_URI.test(prefix)) {
        throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
      }
 
      state.tagMap[handle] = prefix;
    }
};
 
 
function captureSegment(state, start, end, checkJson) {
  var _position, _length, _character, _result;
 
  Eif (start < end) {
    _result = state.input.slice(start, end);
 
    if (checkJson) {
      for (_position = 0, _length = _result.length;
           _position < _length;
           _position += 1) {
        _character = _result.charCodeAt(_position);
        Iif (!(0x09 === _character ||
              0x20 <= _character && _character <= 0x10FFFF)) {
          throwError(state, 'expected valid JSON character');
        }
      }
    }
 
    state.result += _result;
  }
}
 
function mergeMappings(state, destination, source) {
  var sourceKeys, key, index, quantity;
 
  if (!common.isObject(source)) {
    throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
  }
 
  sourceKeys = Object.keys(source);
 
  for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
    key = sourceKeys[index];
 
    if (!_hasOwnProperty.call(destination, key)) {
      destination[key] = source[key];
    }
  }
}
 
function storeMappingPair(state, _result, keyTag, keyNode, valueNode) {
  var index, quantity;
 
  keyNode = String(keyNode);
 
  Iif (null === _result) {
    _result = {};
  }
 
  Iif ('tag:yaml.org,2002:merge' === keyTag) {
    if (Array.isArray(valueNode)) {
      for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
        mergeMappings(state, _result, valueNode[index]);
      }
    } else {
      mergeMappings(state, _result, valueNode);
    }
  } else {
    _result[keyNode] = valueNode;
  }
 
  return _result;
}
 
function readLineBreak(state) {
  var ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Eif (0x0A/* LF */ === ch) {
    state.position++;
  } else if (0x0D/* CR */ === ch) {
    state.position++;
    if (0x0A/* LF */ === state.input.charCodeAt(state.position)) {
      state.position++;
    }
  } else {
    throwError(state, 'a line break is expected');
  }
 
  state.line += 1;
  state.lineStart = state.position;
}
 
function skipSeparationSpace(state, allowComments, checkIndent) {
  var lineBreaks = 0,
      ch = state.input.charCodeAt(state.position);
 
  while (0 !== ch) {
    while (is_WHITE_SPACE(ch)) {
      ch = state.input.charCodeAt(++state.position);
    }
 
    if (allowComments && 0x23/* # */ === ch) {
      do {
        ch = state.input.charCodeAt(++state.position);
      } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && 0 !== ch);
    }
 
    if (is_EOL(ch)) {
      readLineBreak(state);
 
      ch = state.input.charCodeAt(state.position);
      lineBreaks++;
      state.lineIndent = 0;
 
      while (0x20/* Space */ === ch) {
        state.lineIndent++;
        ch = state.input.charCodeAt(++state.position);
      }
    } else {
      break;
    }
  }
 
  Iif (-1 !== checkIndent && 0 !== lineBreaks && state.lineIndent < checkIndent) {
    throwWarning(state, 'deficient indentation');
  }
 
  return lineBreaks;
}
 
function testDocumentSeparator(state) {
  var _position = state.position,
      ch;
 
  ch = state.input.charCodeAt(_position);
 
  // Condition state.position === state.lineStart is tested
  // in parent on each call, for efficiency. No needs to test here again.
  Iif ((0x2D/* - */ === ch || 0x2E/* . */ === ch) &&
      state.input.charCodeAt(_position + 1) === ch &&
      state.input.charCodeAt(_position + 2) === ch) {
 
    _position += 3;
 
    ch = state.input.charCodeAt(_position);
 
    if (ch === 0 || is_WS_OR_EOL(ch)) {
      return true;
    }
  }
 
  return false;
}
 
function writeFoldedLines(state, count) {
  if (1 === count) {
    state.result += ' ';
  } else if (count > 1) {
    state.result += common.repeat('\n', count - 1);
  }
}
 
 
function readPlainScalar(state, nodeIndent, withinFlowCollection) {
  var preceding,
      following,
      captureStart,
      captureEnd,
      hasPendingContent,
      _line,
      _lineStart,
      _lineIndent,
      _kind = state.kind,
      _result = state.result,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Iif (is_WS_OR_EOL(ch)             ||
      is_FLOW_INDICATOR(ch)        ||
      0x23/* # */           === ch ||
      0x26/* & */           === ch ||
      0x2A/* * */           === ch ||
      0x21/* ! */           === ch ||
      0x7C/* | */           === ch ||
      0x3E/* > */           === ch ||
      0x27/* ' */           === ch ||
      0x22/* " */           === ch ||
      0x25/* % */           === ch ||
      0x40/* @ */           === ch ||
      0x60/* ` */           === ch) {
    return false;
  }
 
  Iif (0x3F/* ? */ === ch || 0x2D/* - */ === ch) {
    following = state.input.charCodeAt(state.position + 1);
 
    if (is_WS_OR_EOL(following) ||
        withinFlowCollection && is_FLOW_INDICATOR(following)) {
      return false;
    }
  }
 
  state.kind = 'scalar';
  state.result = '';
  captureStart = captureEnd = state.position;
  hasPendingContent = false;
 
  while (0 !== ch) {
    if (0x3A/* : */ === ch) {
      following = state.input.charCodeAt(state.position + 1);
 
      if (is_WS_OR_EOL(following) ||
          withinFlowCollection && is_FLOW_INDICATOR(following)) {
        break;
      }
 
    } else Iif (0x23/* # */ === ch) {
      preceding = state.input.charCodeAt(state.position - 1);
 
      if (is_WS_OR_EOL(preceding)) {
        break;
      }
 
    } else Iif ((state.position === state.lineStart && testDocumentSeparator(state)) ||
               withinFlowCollection && is_FLOW_INDICATOR(ch)) {
      break;
 
    } else if (is_EOL(ch)) {
      _line = state.line;
      _lineStart = state.lineStart;
      _lineIndent = state.lineIndent;
      skipSeparationSpace(state, false, -1);
 
      Iif (state.lineIndent >= nodeIndent) {
        hasPendingContent = true;
        ch = state.input.charCodeAt(state.position);
        continue;
      } else {
        state.position = captureEnd;
        state.line = _line;
        state.lineStart = _lineStart;
        state.lineIndent = _lineIndent;
        break;
      }
    }
 
    Iif (hasPendingContent) {
      captureSegment(state, captureStart, captureEnd, false);
      writeFoldedLines(state, state.line - _line);
      captureStart = captureEnd = state.position;
      hasPendingContent = false;
    }
 
    if (!is_WHITE_SPACE(ch)) {
      captureEnd = state.position + 1;
    }
 
    ch = state.input.charCodeAt(++state.position);
  }
 
  captureSegment(state, captureStart, captureEnd, false);
 
  Eif (state.result) {
    return true;
  }
 
  state.kind = _kind;
  state.result = _result;
  return false;
}
 
function readSingleQuotedScalar(state, nodeIndent) {
  var ch,
      captureStart, captureEnd;
 
  ch = state.input.charCodeAt(state.position);
 
  if (0x27/* ' */ !== ch) {
    return false;
  }
 
  state.kind = 'scalar';
  state.result = '';
  state.position++;
  captureStart = captureEnd = state.position;
 
  while (0 !== (ch = state.input.charCodeAt(state.position))) {
    if (0x27/* ' */ === ch) {
      captureSegment(state, captureStart, state.position, true);
      ch = state.input.charCodeAt(++state.position);
 
      Iif (0x27/* ' */ === ch) {
        captureStart = captureEnd = state.position;
        state.position++;
      } else {
        return true;
      }
 
    } else Iif (is_EOL(ch)) {
      captureSegment(state, captureStart, captureEnd, true);
      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
      captureStart = captureEnd = state.position;
 
    } else Iif (state.position === state.lineStart && testDocumentSeparator(state)) {
      throwError(state, 'unexpected end of the document within a single quoted scalar');
 
    } else {
      state.position++;
      captureEnd = state.position;
    }
  }
 
  throwError(state, 'unexpected end of the stream within a single quoted scalar');
}
 
function readDoubleQuotedScalar(state, nodeIndent) {
  var captureStart,
      captureEnd,
      hexLength,
      hexResult,
      tmp, tmpEsc,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Eif (0x22/* " */ !== ch) {
    return false;
  }
 
  state.kind = 'scalar';
  state.result = '';
  state.position++;
  captureStart = captureEnd = state.position;
 
  while (0 !== (ch = state.input.charCodeAt(state.position))) {
    if (0x22/* " */ === ch) {
      captureSegment(state, captureStart, state.position, true);
      state.position++;
      return true;
 
    } else if (0x5C/* \ */ === ch) {
      captureSegment(state, captureStart, state.position, true);
      ch = state.input.charCodeAt(++state.position);
 
      if (is_EOL(ch)) {
        skipSeparationSpace(state, false, nodeIndent);
 
        // TODO: rework to inline fn with no type cast?
      } else if (ch < 256 && simpleEscapeCheck[ch]) {
        state.result += simpleEscapeMap[ch];
        state.position++;
 
      } else if ((tmp = escapedHexLen(ch)) > 0) {
        hexLength = tmp;
        hexResult = 0;
 
        for (; hexLength > 0; hexLength--) {
          ch = state.input.charCodeAt(++state.position);
 
          if ((tmp = fromHexCode(ch)) >= 0) {
            hexResult = (hexResult << 4) + tmp;
 
          } else {
            throwError(state, 'expected hexadecimal character');
          }
        }
 
        state.result += charFromCodepoint(hexResult);
 
        state.position++;
 
      } else {
        throwError(state, 'unknown escape sequence');
      }
 
      captureStart = captureEnd = state.position;
 
    } else if (is_EOL(ch)) {
      captureSegment(state, captureStart, captureEnd, true);
      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
      captureStart = captureEnd = state.position;
 
    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
      throwError(state, 'unexpected end of the document within a double quoted scalar');
 
    } else {
      state.position++;
      captureEnd = state.position;
    }
  }
 
  throwError(state, 'unexpected end of the stream within a double quoted scalar');
}
 
function readFlowCollection(state, nodeIndent) {
  var readNext = true,
      _line,
      _tag     = state.tag,
      _result,
      _anchor  = state.anchor,
      following,
      terminator,
      isPair,
      isExplicitPair,
      isMapping,
      keyNode,
      keyTag,
      valueNode,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Iif (ch === 0x5B/* [ */) {
    terminator = 0x5D;/* ] */
    isMapping = false;
    _result = [];
  } else Iif (ch === 0x7B/* { */) {
    terminator = 0x7D;/* } */
    isMapping = true;
    _result = {};
  } else {
    return false;
  }
 
  if (null !== state.anchor) {
    state.anchorMap[state.anchor] = _result;
  }
 
  ch = state.input.charCodeAt(++state.position);
 
  while (0 !== ch) {
    skipSeparationSpace(state, true, nodeIndent);
 
    ch = state.input.charCodeAt(state.position);
 
    if (ch === terminator) {
      state.position++;
      state.tag = _tag;
      state.anchor = _anchor;
      state.kind = isMapping ? 'mapping' : 'sequence';
      state.result = _result;
      return true;
    } else if (!readNext) {
      throwError(state, 'missed comma between flow collection entries');
    }
 
    keyTag = keyNode = valueNode = null;
    isPair = isExplicitPair = false;
 
    if (0x3F/* ? */ === ch) {
      following = state.input.charCodeAt(state.position + 1);
 
      if (is_WS_OR_EOL(following)) {
        isPair = isExplicitPair = true;
        state.position++;
        skipSeparationSpace(state, true, nodeIndent);
      }
    }
 
    _line = state.line;
    composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
    keyTag = state.tag;
    keyNode = state.result;
    skipSeparationSpace(state, true, nodeIndent);
 
    ch = state.input.charCodeAt(state.position);
 
    if ((isExplicitPair || state.line === _line) && 0x3A/* : */ === ch) {
      isPair = true;
      ch = state.input.charCodeAt(++state.position);
      skipSeparationSpace(state, true, nodeIndent);
      composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
      valueNode = state.result;
    }
 
    if (isMapping) {
      storeMappingPair(state, _result, keyTag, keyNode, valueNode);
    } else if (isPair) {
      _result.push(storeMappingPair(state, null, keyTag, keyNode, valueNode));
    } else {
      _result.push(keyNode);
    }
 
    skipSeparationSpace(state, true, nodeIndent);
 
    ch = state.input.charCodeAt(state.position);
 
    if (0x2C/* , */ === ch) {
      readNext = true;
      ch = state.input.charCodeAt(++state.position);
    } else {
      readNext = false;
    }
  }
 
  throwError(state, 'unexpected end of the stream within a flow collection');
}
 
function readBlockScalar(state, nodeIndent) {
  var captureStart,
      folding,
      chomping       = CHOMPING_CLIP,
      detectedIndent = false,
      textIndent     = nodeIndent,
      emptyLines     = 0,
      atMoreIndented = false,
      tmp,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  if (ch === 0x7C/* | */) {
    folding = false;
  } else Iif (ch === 0x3E/* > */) {
    folding = true;
  } else {
    return false;
  }
 
  state.kind = 'scalar';
  state.result = '';
 
  while (0 !== ch) {
    ch = state.input.charCodeAt(++state.position);
 
    Iif (0x2B/* + */ === ch || 0x2D/* - */ === ch) {
      if (CHOMPING_CLIP === chomping) {
        chomping = (0x2B/* + */ === ch) ? CHOMPING_KEEP : CHOMPING_STRIP;
      } else {
        throwError(state, 'repeat of a chomping mode identifier');
      }
 
    } else Iif ((tmp = fromDecimalCode(ch)) >= 0) {
      if (tmp === 0) {
        throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
      } else if (!detectedIndent) {
        textIndent = nodeIndent + tmp - 1;
        detectedIndent = true;
      } else {
        throwError(state, 'repeat of an indentation width identifier');
      }
 
    } else {
      break;
    }
  }
 
  Iif (is_WHITE_SPACE(ch)) {
    do { ch = state.input.charCodeAt(++state.position); }
    while (is_WHITE_SPACE(ch));
 
    if (0x23/* # */ === ch) {
      do { ch = state.input.charCodeAt(++state.position); }
      while (!is_EOL(ch) && (0 !== ch));
    }
  }
 
  while (0 !== ch) {
    readLineBreak(state);
    state.lineIndent = 0;
 
    ch = state.input.charCodeAt(state.position);
 
    while ((!detectedIndent || state.lineIndent < textIndent) &&
           (0x20/* Space */ === ch)) {
      state.lineIndent++;
      ch = state.input.charCodeAt(++state.position);
    }
 
    if (!detectedIndent && state.lineIndent > textIndent) {
      textIndent = state.lineIndent;
    }
 
    if (is_EOL(ch)) {
      emptyLines++;
      continue;
    }
 
    // End of the scalar.
    if (state.lineIndent < textIndent) {
 
      // Perform the chomping.
      Iif (chomping === CHOMPING_KEEP) {
        state.result += common.repeat('\n', emptyLines);
      } else Eif (chomping === CHOMPING_CLIP) {
        Eif (detectedIndent) { // i.e. only if the scalar is not empty.
          state.result += '\n';
        }
      }
 
      // Break this `while` cycle and go to the funciton's epilogue.
      break;
    }
 
    // Folded style: use fancy rules to handle line breaks.
    Iif (folding) {
 
      // Lines starting with white space characters (more-indented lines) are not folded.
      if (is_WHITE_SPACE(ch)) {
        atMoreIndented = true;
        state.result += common.repeat('\n', emptyLines + 1);
 
      // End of more-indented block.
      } else if (atMoreIndented) {
        atMoreIndented = false;
        state.result += common.repeat('\n', emptyLines + 1);
 
      // Just one line break - perceive as the same line.
      } else if (0 === emptyLines) {
        if (detectedIndent) { // i.e. only if we have already read some scalar content.
          state.result += ' ';
        }
 
      // Several line breaks - perceive as different lines.
      } else {
        state.result += common.repeat('\n', emptyLines);
      }
 
    // Literal style: just add exact number of line breaks between content lines.
    } else if (detectedIndent) {
      // If current line isn't the first one - count line break from the last content line.
      state.result += common.repeat('\n', emptyLines + 1);
    } else {
      // In case of the first content line - count only empty lines.
    }
 
    detectedIndent = true;
    emptyLines = 0;
    captureStart = state.position;
 
    while (!is_EOL(ch) && (0 !== ch)) {
      ch = state.input.charCodeAt(++state.position);
    }
 
    captureSegment(state, captureStart, state.position, false);
  }
 
  return true;
}
 
function readBlockSequence(state, nodeIndent) {
  var _line,
      _tag      = state.tag,
      _anchor   = state.anchor,
      _result   = [],
      following,
      detected  = false,
      ch;
 
  Iif (null !== state.anchor) {
    state.anchorMap[state.anchor] = _result;
  }
 
  ch = state.input.charCodeAt(state.position);
 
  while (0 !== ch) {
 
    if (0x2D/* - */ !== ch) {
      break;
    }
 
    following = state.input.charCodeAt(state.position + 1);
 
    Iif (!is_WS_OR_EOL(following)) {
      break;
    }
 
    detected = true;
    state.position++;
 
    Iif (skipSeparationSpace(state, true, -1)) {
      if (state.lineIndent <= nodeIndent) {
        _result.push(null);
        ch = state.input.charCodeAt(state.position);
        continue;
      }
    }
 
    _line = state.line;
    composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
    _result.push(state.result);
    skipSeparationSpace(state, true, -1);
 
    ch = state.input.charCodeAt(state.position);
 
    Iif ((state.line === _line || state.lineIndent > nodeIndent) && (0 !== ch)) {
      throwError(state, 'bad indentation of a sequence entry');
    } else if (state.lineIndent < nodeIndent) {
      break;
    }
  }
 
  if (detected) {
    state.tag = _tag;
    state.anchor = _anchor;
    state.kind = 'sequence';
    state.result = _result;
    return true;
  }
  return false;
}
 
function readBlockMapping(state, nodeIndent, flowIndent) {
  var following,
      allowCompact,
      _line,
      _tag          = state.tag,
      _anchor       = state.anchor,
      _result       = {},
      keyTag        = null,
      keyNode       = null,
      valueNode     = null,
      atExplicitKey = false,
      detected      = false,
      ch;
 
  Iif (null !== state.anchor) {
    state.anchorMap[state.anchor] = _result;
  }
 
  ch = state.input.charCodeAt(state.position);
 
  while (0 !== ch) {
    following = state.input.charCodeAt(state.position + 1);
    _line = state.line; // Save the current line.
 
    //
    // Explicit notation case. There are two separate blocks:
    // first for the key (denoted by "?") and second for the value (denoted by ":")
    //
    Iif ((0x3F/* ? */ === ch || 0x3A/* : */  === ch) && is_WS_OR_EOL(following)) {
 
      if (0x3F/* ? */ === ch) {
        if (atExplicitKey) {
          storeMappingPair(state, _result, keyTag, keyNode, null);
          keyTag = keyNode = valueNode = null;
        }
 
        detected = true;
        atExplicitKey = true;
        allowCompact = true;
 
      } else if (atExplicitKey) {
        // i.e. 0x3A/* : */ === character after the explicit key.
        atExplicitKey = false;
        allowCompact = true;
 
      } else {
        throwError(state, 'incomplete explicit mapping pair; a key node is missed');
      }
 
      state.position += 1;
      ch = following;
 
    //
    // Implicit notation case. Flow-style node as the key first, then ":", and the value.
    //
    } else Eif (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
 
      Eif (state.line === _line) {
        ch = state.input.charCodeAt(state.position);
 
        while (is_WHITE_SPACE(ch)) {
          ch = state.input.charCodeAt(++state.position);
        }
 
        if (0x3A/* : */ === ch) {
          ch = state.input.charCodeAt(++state.position);
 
          Iif (!is_WS_OR_EOL(ch)) {
            throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
          }
 
          Iif (atExplicitKey) {
            storeMappingPair(state, _result, keyTag, keyNode, null);
            keyTag = keyNode = valueNode = null;
          }
 
          detected = true;
          atExplicitKey = false;
          allowCompact = false;
          keyTag = state.tag;
          keyNode = state.result;
 
        } else Iif (detected) {
          throwError(state, 'can not read an implicit mapping pair; a colon is missed');
 
        } else {
          state.tag = _tag;
          state.anchor = _anchor;
          return true; // Keep the result of `composeNode`.
        }
 
      } else if (detected) {
        throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');
 
      } else {
        state.tag = _tag;
        state.anchor = _anchor;
        return true; // Keep the result of `composeNode`.
      }
 
    } else {
      break; // Reading is done. Go to the epilogue.
    }
 
    //
    // Common reading code for both explicit and implicit notations.
    //
    Eif (state.line === _line || state.lineIndent > nodeIndent) {
      Eif (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
        Iif (atExplicitKey) {
          keyNode = state.result;
        } else {
          valueNode = state.result;
        }
      }
 
      Eif (!atExplicitKey) {
        storeMappingPair(state, _result, keyTag, keyNode, valueNode);
        keyTag = keyNode = valueNode = null;
      }
 
      skipSeparationSpace(state, true, -1);
      ch = state.input.charCodeAt(state.position);
    }
 
    Iif (state.lineIndent > nodeIndent && (0 !== ch)) {
      throwError(state, 'bad indentation of a mapping entry');
    } else if (state.lineIndent < nodeIndent) {
      break;
    }
  }
 
  //
  // Epilogue.
  //
 
  // Special case: last mapping's node contains only the key in explicit notation.
  Iif (atExplicitKey) {
    storeMappingPair(state, _result, keyTag, keyNode, null);
  }
 
  // Expose the resulting mapping.
  Eif (detected) {
    state.tag = _tag;
    state.anchor = _anchor;
    state.kind = 'mapping';
    state.result = _result;
  }
 
  return detected;
}
 
function readTagProperty(state) {
  var _position,
      isVerbatim = false,
      isNamed    = false,
      tagHandle,
      tagName,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Eif (0x21/* ! */ !== ch) {
    return false;
  }
 
  if (null !== state.tag) {
    throwError(state, 'duplication of a tag property');
  }
 
  ch = state.input.charCodeAt(++state.position);
 
  if (0x3C/* < */ === ch) {
    isVerbatim = true;
    ch = state.input.charCodeAt(++state.position);
 
  } else if (0x21/* ! */ === ch) {
    isNamed = true;
    tagHandle = '!!';
    ch = state.input.charCodeAt(++state.position);
 
  } else {
    tagHandle = '!';
  }
 
  _position = state.position;
 
  if (isVerbatim) {
    do { ch = state.input.charCodeAt(++state.position); }
    while (0 !== ch && 0x3E/* > */ !== ch);
 
    if (state.position < state.length) {
      tagName = state.input.slice(_position, state.position);
      ch = state.input.charCodeAt(++state.position);
    } else {
      throwError(state, 'unexpected end of the stream within a verbatim tag');
    }
  } else {
    while (0 !== ch && !is_WS_OR_EOL(ch)) {
 
      if (0x21/* ! */ === ch) {
        if (!isNamed) {
          tagHandle = state.input.slice(_position - 1, state.position + 1);
 
          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
            throwError(state, 'named tag handle cannot contain such characters');
          }
 
          isNamed = true;
          _position = state.position + 1;
        } else {
          throwError(state, 'tag suffix cannot contain exclamation marks');
        }
      }
 
      ch = state.input.charCodeAt(++state.position);
    }
 
    tagName = state.input.slice(_position, state.position);
 
    if (PATTERN_FLOW_INDICATORS.test(tagName)) {
      throwError(state, 'tag suffix cannot contain flow indicator characters');
    }
  }
 
  if (tagName && !PATTERN_TAG_URI.test(tagName)) {
    throwError(state, 'tag name cannot contain such characters: ' + tagName);
  }
 
  if (isVerbatim) {
    state.tag = tagName;
 
  } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
    state.tag = state.tagMap[tagHandle] + tagName;
 
  } else if ('!' === tagHandle) {
    state.tag = '!' + tagName;
 
  } else if ('!!' === tagHandle) {
    state.tag = 'tag:yaml.org,2002:' + tagName;
 
  } else {
    throwError(state, 'undeclared tag handle "' + tagHandle + '"');
  }
 
  return true;
}
 
function readAnchorProperty(state) {
  var _position,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Eif (0x26/* & */ !== ch) {
    return false;
  }
 
  if (null !== state.anchor) {
    throwError(state, 'duplication of an anchor property');
  }
 
  ch = state.input.charCodeAt(++state.position);
  _position = state.position;
 
  while (0 !== ch && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
    ch = state.input.charCodeAt(++state.position);
  }
 
  if (state.position === _position) {
    throwError(state, 'name of an anchor node must contain at least one character');
  }
 
  state.anchor = state.input.slice(_position, state.position);
  return true;
}
 
function readAlias(state) {
  var _position, alias,
      len = state.length,
      input = state.input,
      ch;
 
  ch = state.input.charCodeAt(state.position);
 
  Eif (0x2A/* * */ !== ch) {
    return false;
  }
 
  ch = state.input.charCodeAt(++state.position);
  _position = state.position;
 
  while (0 !== ch && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
    ch = state.input.charCodeAt(++state.position);
  }
 
  if (state.position === _position) {
    throwError(state, 'name of an alias node must contain at least one character');
  }
 
  alias = state.input.slice(_position, state.position);
 
  if (!state.anchorMap.hasOwnProperty(alias)) {
    throwError(state, 'unidentified alias "' + alias + '"');
  }
 
  state.result = state.anchorMap[alias];
  skipSeparationSpace(state, true, -1);
  return true;
}
 
function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
  var allowBlockStyles,
      allowBlockScalars,
      allowBlockCollections,
      indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
      atNewLine  = false,
      hasContent = false,
      typeIndex,
      typeQuantity,
      type,
      flowIndent,
      blockIndent,
      _result;
 
  state.tag    = null;
  state.anchor = null;
  state.kind   = null;
  state.result = null;
 
  allowBlockStyles = allowBlockScalars = allowBlockCollections =
    CONTEXT_BLOCK_OUT === nodeContext ||
    CONTEXT_BLOCK_IN  === nodeContext;
 
  if (allowToSeek) {
    if (skipSeparationSpace(state, true, -1)) {
      atNewLine = true;
 
      Eif (state.lineIndent > parentIndent) {
        indentStatus = 1;
      } else if (state.lineIndent === parentIndent) {
        indentStatus = 0;
      } else if (state.lineIndent < parentIndent) {
        indentStatus = -1;
      }
    }
  }
 
  Eif (1 === indentStatus) {
    while (readTagProperty(state) || readAnchorProperty(state)) {
      if (skipSeparationSpace(state, true, -1)) {
        atNewLine = true;
        allowBlockCollections = allowBlockStyles;
 
        if (state.lineIndent > parentIndent) {
          indentStatus = 1;
        } else if (state.lineIndent === parentIndent) {
          indentStatus = 0;
        } else if (state.lineIndent < parentIndent) {
          indentStatus = -1;
        }
      } else {
        allowBlockCollections = false;
      }
    }
  }
 
  if (allowBlockCollections) {
    allowBlockCollections = atNewLine || allowCompact;
  }
 
  Eif (1 === indentStatus || CONTEXT_BLOCK_OUT === nodeContext) {
    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
      flowIndent = parentIndent;
    } else {
      flowIndent = parentIndent + 1;
    }
 
    blockIndent = state.position - state.lineStart;
 
    Eif (1 === indentStatus) {
      if (allowBlockCollections &&
          (readBlockSequence(state, blockIndent) ||
           readBlockMapping(state, blockIndent, flowIndent)) ||
          readFlowCollection(state, flowIndent)) {
        hasContent = true;
      } else {
        if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
            readSingleQuotedScalar(state, flowIndent) ||
            readDoubleQuotedScalar(state, flowIndent)) {
          hasContent = true;
 
        } else Iif (readAlias(state)) {
          hasContent = true;
 
          if (null !== state.tag || null !== state.anchor) {
            throwError(state, 'alias node should not have any properties');
          }
 
        } else Eif (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
          hasContent = true;
 
          Eif (null === state.tag) {
            state.tag = '?';
          }
        }
 
        Iif (null !== state.anchor) {
          state.anchorMap[state.anchor] = state.result;
        }
      }
    } else if (0 === indentStatus) {
      // Special case: block sequences are allowed to have same indentation level as the parent.
      // http://www.yaml.org/spec/1.2/spec.html#id2799784
      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
    }
  }
 
  if (null !== state.tag && '!' !== state.tag) {
    Eif ('?' === state.tag) {
      for (typeIndex = 0, typeQuantity = state.implicitTypes.length;
           typeIndex < typeQuantity;
           typeIndex += 1) {
        type = state.implicitTypes[typeIndex];
 
        // Implicit resolving is not allowed for non-scalar types, and '?'
        // non-specific tag is only assigned to plain scalars. So, it isn't
        // needed to check for 'kind' conformity.
 
        if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
          state.result = type.construct(state.result);
          state.tag = type.tag;
          Iif (null !== state.anchor) {
            state.anchorMap[state.anchor] = state.result;
          }
          break;
        }
      }
    } else if (_hasOwnProperty.call(state.typeMap, state.tag)) {
      type = state.typeMap[state.tag];
 
      if (null !== state.result && type.kind !== state.kind) {
        throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
      }
 
      if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched
        throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
      } else {
        state.result = type.construct(state.result);
        if (null !== state.anchor) {
          state.anchorMap[state.anchor] = state.result;
        }
      }
    } else {
      throwWarning(state, 'unknown tag !<' + state.tag + '>');
    }
  }
 
  return null !== state.tag || null !== state.anchor || hasContent;
}
 
function readDocument(state) {
  var documentStart = state.position,
      _position,
      directiveName,
      directiveArgs,
      hasDirectives = false,
      ch;
 
  state.version = null;
  state.checkLineBreaks = state.legacy;
  state.tagMap = {};
  state.anchorMap = {};
 
  while (0 !== (ch = state.input.charCodeAt(state.position))) {
    skipSeparationSpace(state, true, -1);
 
    ch = state.input.charCodeAt(state.position);
 
    Eif (state.lineIndent > 0 || 0x25/* % */ !== ch) {
      break;
    }
 
    hasDirectives = true;
    ch = state.input.charCodeAt(++state.position);
    _position = state.position;
 
    while (0 !== ch && !is_WS_OR_EOL(ch)) {
      ch = state.input.charCodeAt(++state.position);
    }
 
    directiveName = state.input.slice(_position, state.position);
    directiveArgs = [];
 
    if (directiveName.length < 1) {
      throwError(state, 'directive name must not be less than one character in length');
    }
 
    while (0 !== ch) {
      while (is_WHITE_SPACE(ch)) {
        ch = state.input.charCodeAt(++state.position);
      }
 
      if (0x23/* # */ === ch) {
        do { ch = state.input.charCodeAt(++state.position); }
        while (0 !== ch && !is_EOL(ch));
        break;
      }
 
      if (is_EOL(ch)) {
        break;
      }
 
      _position = state.position;
 
      while (0 !== ch && !is_WS_OR_EOL(ch)) {
        ch = state.input.charCodeAt(++state.position);
      }
 
      directiveArgs.push(state.input.slice(_position, state.position));
    }
 
    if (0 !== ch) {
      readLineBreak(state);
    }
 
    if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
      directiveHandlers[directiveName](state, directiveName, directiveArgs);
    } else {
      throwWarning(state, 'unknown document directive "' + directiveName + '"');
    }
  }
 
  skipSeparationSpace(state, true, -1);
 
  Iif (0 === state.lineIndent &&
      0x2D/* - */ === state.input.charCodeAt(state.position) &&
      0x2D/* - */ === state.input.charCodeAt(state.position + 1) &&
      0x2D/* - */ === state.input.charCodeAt(state.position + 2)) {
    state.position += 3;
    skipSeparationSpace(state, true, -1);
 
  } else Iif (hasDirectives) {
    throwError(state, 'directives end mark is expected');
  }
 
  composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
  skipSeparationSpace(state, true, -1);
 
  Iif (state.checkLineBreaks &&
      PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
    throwWarning(state, 'non-ASCII line breaks are interpreted as content');
  }
 
  state.documents.push(state.result);
 
  Iif (state.position === state.lineStart && testDocumentSeparator(state)) {
 
    if (0x2E/* . */ === state.input.charCodeAt(state.position)) {
      state.position += 3;
      skipSeparationSpace(state, true, -1);
    }
    return;
  }
 
  Iif (state.position < (state.length - 1)) {
    throwError(state, 'end of the stream or a document separator is expected');
  } else {
    return;
  }
}
 
 
function loadDocuments(input, options) {
  input = String(input);
  options = options || {};
 
  Eif (input.length !== 0) {
 
    // Add tailing `\n` if not exists
    Iif (0x0A/* LF */ !== input.charCodeAt(input.length - 1) &&
        0x0D/* CR */ !== input.charCodeAt(input.length - 1)) {
      input += '\n';
    }
 
    // Strip BOM
    Iif (input.charCodeAt(0) === 0xFEFF) {
      input = input.slice(1);
    }
  }
 
  var state = new State(input, options);
 
  Iif (PATTERN_NON_PRINTABLE.test(state.input)) {
    throwError(state, 'the stream contains non-printable characters');
  }
 
  // Use 0 as string terminator. That significantly simplifies bounds check.
  state.input += '\0';
 
  while (0x20/* Space */ === state.input.charCodeAt(state.position)) {
    state.lineIndent += 1;
    state.position += 1;
  }
 
  while (state.position < (state.length - 1)) {
    readDocument(state);
  }
 
  return state.documents;
}
 
 
function loadAll(input, iterator, options) {
  var documents = loadDocuments(input, options), index, length;
 
  for (index = 0, length = documents.length; index < length; index += 1) {
    iterator(documents[index]);
  }
}
 
 
function load(input, options) {
  var documents = loadDocuments(input, options), index, length;
 
  Iif (0 === documents.length) {
    /*eslint-disable no-undefined*/
    return undefined;
  } else Eif (1 === documents.length) {
    return documents[0];
  }
  throw new YAMLException('expected a single document in the stream, but found more');
}
 
 
function safeLoadAll(input, output, options) {
  loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
 
 
function safeLoad(input, options) {
  return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));
}
 
 
module.exports.loadAll     = loadAll;
module.exports.load        = load;
module.exports.safeLoadAll = safeLoadAll;
module.exports.safeLoad    = safeLoad;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/mark.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/mark.js

Statements: 11.9% (5 / 42)      Branches: 0% (0 / 20)      Functions: 0% (0 / 3)      Lines: 11.9% (5 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80      1     1                 1                                                                                 1                                         1    
'use strict';
 
 
var common = require('./common');
 
 
function Mark(name, buffer, position, line, column) {
  this.name     = name;
  this.buffer   = buffer;
  this.position = position;
  this.line     = line;
  this.column   = column;
}
 
 
Mark.prototype.getSnippet = function getSnippet(indent, maxLength) {
  var head, start, tail, end, snippet;
 
  if (!this.buffer) {
    return null;
  }
 
  indent = indent || 4;
  maxLength = maxLength || 75;
 
  head = '';
  start = this.position;
 
  while (start > 0 && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1))) {
    start -= 1;
    if (this.position - start > (maxLength / 2 - 1)) {
      head = ' ... ';
      start += 5;
      break;
    }
  }
 
  tail = '';
  end = this.position;
 
  while (end < this.buffer.length && -1 === '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end))) {
    end += 1;
    if (end - this.position > (maxLength / 2 - 1)) {
      tail = ' ... ';
      end -= 5;
      break;
    }
  }
 
  snippet = this.buffer.slice(start, end);
 
  return common.repeat(' ', indent) + head + snippet + tail + '\n' +
         common.repeat(' ', indent + this.position - start + head.length) + '^';
};
 
 
Mark.prototype.toString = function toString(compact) {
  var snippet, where = '';
 
  if (this.name) {
    where += 'in "' + this.name + '" ';
  }
 
  where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1);
 
  if (!compact) {
    snippet = this.getSnippet();
 
    if (snippet) {
      where += ':\n' + snippet;
    }
  }
 
  return where;
};
 
 
module.exports = Mark;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema.js

Statements: 61.54% (32 / 52)      Branches: 47.37% (9 / 19)      Functions: 75% (9 / 12)      Lines: 64% (32 / 50)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106        1 1 1     1 30   30 20     30 46 117         46     30 106         1 5   1 46     5 10     5       1 5 5 5   5 6         5 5 5       1     1                                                                       1    
'use strict';
 
/*eslint-disable max-len*/
 
var common        = require('./common');
var YAMLException = require('./exception');
var Type          = require('./type');
 
 
function compileList(schema, name, result) {
  var exclude = [];
 
  schema.include.forEach(function (includedSchema) {
    result = compileList(includedSchema, name, result);
  });
 
  schema[name].forEach(function (currentType) {
    result.forEach(function (previousType, previousIndex) {
      Iif (previousType.tag === currentType.tag) {
        exclude.push(previousIndex);
      }
    });
 
    result.push(currentType);
  });
 
  return result.filter(function (type, index) {
    return -1 === exclude.indexOf(index);
  });
}
 
 
function compileMap(/* lists... */) {
  var result = {}, index, length;
 
  function collectType(type) {
    result[type.tag] = type;
  }
 
  for (index = 0, length = arguments.length; index < length; index += 1) {
    arguments[index].forEach(collectType);
  }
 
  return result;
}
 
 
function Schema(definition) {
  this.include  = definition.include  || [];
  this.implicit = definition.implicit || [];
  this.explicit = definition.explicit || [];
 
  this.implicit.forEach(function (type) {
    Iif (type.loadKind && 'scalar' !== type.loadKind) {
      throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
    }
  });
 
  this.compiledImplicit = compileList(this, 'implicit', []);
  this.compiledExplicit = compileList(this, 'explicit', []);
  this.compiledTypeMap  = compileMap(this.compiledImplicit, this.compiledExplicit);
}
 
 
Schema.DEFAULT = null;
 
 
Schema.create = function createSchema() {
  var schemas, types;
 
  switch (arguments.length) {
  case 1:
    schemas = Schema.DEFAULT;
    types = arguments[0];
    break;
 
  case 2:
    schemas = arguments[0];
    types = arguments[1];
    break;
 
  default:
    throw new YAMLException('Wrong number of arguments for Schema.create function');
  }
 
  schemas = common.toArray(schemas);
  types = common.toArray(types);
 
  if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
    throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
  }
 
  if (!types.every(function (type) { return type instanceof Type; })) {
    throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
  }
 
  return new Schema({
    include: schemas,
    explicit: types
  });
};
 
 
module.exports = Schema;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type.js

Statements: 86.21% (25 / 29)      Branches: 83.33% (20 / 24)      Functions: 71.43% (5 / 7)      Lines: 92.59% (25 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63    1   1                     1           1 16   16 1 4 8         16     1 16   16 67           16 16 16 16 16 16 16 16 16   16         1    
'use strict';
 
var YAMLException = require('./exception');
 
var TYPE_CONSTRUCTOR_OPTIONS = [
  'kind',
  'resolve',
  'construct',
  'instanceOf',
  'predicate',
  'represent',
  'defaultStyle',
  'styleAliases'
];
 
var YAML_NODE_KINDS = [
  'scalar',
  'sequence',
  'mapping'
];
 
function compileStyleAliases(map) {
  var result = {};
 
  if (null !== map) {
    Object.keys(map).forEach(function (style) {
      map[style].forEach(function (alias) {
        result[String(alias)] = style;
      });
    });
  }
 
  return result;
}
 
function Type(tag, options) {
  options = options || {};
 
  Object.keys(options).forEach(function (name) {
    Iif (-1 === TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)) {
      throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
    }
  });
 
  // TODO: Add tag format check.
  this.tag          = tag;
  this.kind         = options['kind']         || null;
  this.resolve      = options['resolve']      || function () { return true; };
  this.construct    = options['construct']    || function (data) { return data; };
  this.instanceOf   = options['instanceOf']   || null;
  this.predicate    = options['predicate']    || null;
  this.represent    = options['represent']    || null;
  this.defaultStyle = options['defaultStyle'] || null;
  this.styleAliases = compileStyleAliases(options['styleAliases'] || null);
 
  Iif (-1 === YAML_NODE_KINDS.indexOf(this.kind)) {
    throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
  }
}
 
module.exports = Type;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/

Statements: 100% (10 / 10)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (10 / 10)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/
File Statements Branches Functions Lines
core.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
default_full.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
default_safe.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
failsafe.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
json.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/core.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/core.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20                    1     1            
// Standard YAML's Core schema.
// http://www.yaml.org/spec/1.2/spec.html#id2804923
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, Core schema has no distinctions from JSON schema is JS-YAML.
 
 
'use strict';
 
 
var Schema = require('../schema');
 
 
module.exports = new Schema({
  include: [
    require('./json')
  ]
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/default_full.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/default_full.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                        1     1                      
// JS-YAML's default schema for `load` function.
// It is not described in the YAML specification.
//
// This schema is based on JS-YAML's default safe schema and includes
// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function.
//
// Also this schema is used as default base schema at `Schema.create` function.
 
 
'use strict';
 
 
var Schema = require('../schema');
 
 
module.exports = Schema.DEFAULT = new Schema({
  include: [
    require('./default_safe')
  ],
  explicit: [
    require('../type/js/undefined'),
    require('../type/js/regexp'),
    require('../type/js/function')
  ]
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30                    1     1                                
// JS-YAML's default schema for `safeLoad` function.
// It is not described in the YAML specification.
//
// This schema is based on standard YAML's Core schema and includes most of
// extra types described at YAML tag repository. (http://yaml.org/type/)
 
 
'use strict';
 
 
var Schema = require('../schema');
 
 
module.exports = new Schema({
  include: [
    require('./core')
  ],
  implicit: [
    require('../type/timestamp'),
    require('../type/merge')
  ],
  explicit: [
    require('../type/binary'),
    require('../type/omap'),
    require('../type/pairs'),
    require('../type/set')
  ]
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19              1     1                
// Standard YAML's Failsafe schema.
// http://www.yaml.org/spec/1.2/spec.html#id2802346
 
 
'use strict';
 
 
var Schema = require('../schema');
 
 
module.exports = new Schema({
  explicit: [
    require('../type/str'),
    require('../type/seq'),
    require('../type/map')
  ]
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/json.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/schema/json.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                      1     1                        
// Standard YAML's JSON schema.
// http://www.yaml.org/spec/1.2/spec.html#id2803231
//
// NOTE: JS-YAML does not support schema-specific tag resolution restrictions.
// So, this schema is not such strict as defined in the YAML specification.
// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc.
 
 
'use strict';
 
 
var Schema = require('../schema');
 
 
module.exports = new Schema({
  include: [
    require('./failsafe')
  ],
  implicit: [
    require('../type/null'),
    require('../type/bool'),
    require('../type/int'),
    require('../type/float')
  ]
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/

Statements: 26.5% (97 / 366)      Branches: 15.45% (34 / 220)      Functions: 16.67% (8 / 48)      Lines: 27.4% (97 / 354)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/
File Statements Branches Functions Lines
binary.js 12.31% (8 / 65) 0% (0 / 30) 0% (0 / 4) 12.7% (8 / 63)
bool.js 64.29% (9 / 14) 52.63% (10 / 19) 33.33% (2 / 6) 64.29% (9 / 14)
float.js 22.64% (12 / 53) 5.56% (2 / 36) 16.67% (1 / 6) 22.64% (12 / 53)
int.js 23.47% (23 / 98) 16.9% (12 / 71) 16.67% (2 / 12) 26.14% (23 / 88)
map.js 66.67% (2 / 3) 0% (0 / 2) 0% (0 / 1) 66.67% (2 / 3)
merge.js 100% (4 / 4) 100% (2 / 2) 100% (1 / 1) 100% (4 / 4)
null.js 53.33% (8 / 15) 75% (6 / 8) 14.29% (1 / 7) 53.33% (8 / 15)
omap.js 23.08% (6 / 26) 0% (0 / 14) 0% (0 / 2) 23.08% (6 / 26)
pairs.js 18.52% (5 / 27) 0% (0 / 8) 0% (0 / 2) 18.52% (5 / 27)
seq.js 66.67% (2 / 3) 0% (0 / 2) 0% (0 / 1) 66.67% (2 / 3)
set.js 35.71% (5 / 14) 0% (0 / 8) 0% (0 / 2) 35.71% (5 / 14)
str.js 66.67% (2 / 3) 0% (0 / 2) 0% (0 / 1) 66.67% (2 / 3)
timestamp.js 26.83% (11 / 41) 11.11% (2 / 18) 33.33% (1 / 3) 26.83% (11 / 41)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/binary.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/binary.js

Statements: 12.31% (8 / 65)      Branches: 0% (0 / 30)      Functions: 0% (0 / 4)      Lines: 12.7% (8 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136            1 1       1     1                                               1                                                                                     1                                                                                   1       1                
'use strict';
 
/*eslint-disable no-bitwise*/
 
// A trick for browserified version.
// Since we make browserifier to ignore `buffer` module, NodeBuffer will be undefined
var NodeBuffer = require('buffer').Buffer;
var Type       = require('../type');
 
 
// [ 64, 65, 66 ] -> [ padding, CR, LF ]
var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';
 
 
function resolveYamlBinary(data) {
  if (null === data) {
    return false;
  }
 
  var code, idx, bitlen = 0, len = 0, max = data.length, map = BASE64_MAP;
 
  // Convert one by one.
  for (idx = 0; idx < max; idx++) {
    code = map.indexOf(data.charAt(idx));
 
    // Skip CR/LF
    if (code > 64) { continue; }
 
    // Fail on illegal characters
    if (code < 0) { return false; }
 
    bitlen += 6;
  }
 
  // If there are any bits left, source was corrupted
  return (bitlen % 8) === 0;
}
 
function constructYamlBinary(data) {
  var code, idx, tailbits,
      input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
      max = input.length,
      map = BASE64_MAP,
      bits = 0,
      result = [];
 
  // Collect by 6*4 bits (3 bytes)
 
  for (idx = 0; idx < max; idx++) {
    if ((idx % 4 === 0) && idx) {
      result.push((bits >> 16) & 0xFF);
      result.push((bits >> 8) & 0xFF);
      result.push(bits & 0xFF);
    }
 
    bits = (bits << 6) | map.indexOf(input.charAt(idx));
  }
 
  // Dump tail
 
  tailbits = (max % 4) * 6;
 
  if (tailbits === 0) {
    result.push((bits >> 16) & 0xFF);
    result.push((bits >> 8) & 0xFF);
    result.push(bits & 0xFF);
  } else if (tailbits === 18) {
    result.push((bits >> 10) & 0xFF);
    result.push((bits >> 2) & 0xFF);
  } else if (tailbits === 12) {
    result.push((bits >> 4) & 0xFF);
  }
 
  // Wrap into Buffer for NodeJS and leave Array for browser
  if (NodeBuffer) {
    return new NodeBuffer(result);
  }
 
  return result;
}
 
function representYamlBinary(object /*, style*/) {
  var result = '', bits = 0, idx, tail,
      max = object.length,
      map = BASE64_MAP;
 
  // Convert every three bytes to 4 ASCII characters.
 
  for (idx = 0; idx < max; idx++) {
    if ((idx % 3 === 0) && idx) {
      result += map[(bits >> 18) & 0x3F];
      result += map[(bits >> 12) & 0x3F];
      result += map[(bits >> 6) & 0x3F];
      result += map[bits & 0x3F];
    }
 
    bits = (bits << 8) + object[idx];
  }
 
  // Dump tail
 
  tail = max % 3;
 
  if (tail === 0) {
    result += map[(bits >> 18) & 0x3F];
    result += map[(bits >> 12) & 0x3F];
    result += map[(bits >> 6) & 0x3F];
    result += map[bits & 0x3F];
  } else if (tail === 2) {
    result += map[(bits >> 10) & 0x3F];
    result += map[(bits >> 4) & 0x3F];
    result += map[(bits << 2) & 0x3F];
    result += map[64];
  } else if (tail === 1) {
    result += map[(bits >> 2) & 0x3F];
    result += map[(bits << 4) & 0x3F];
    result += map[64];
    result += map[64];
  }
 
  return result;
}
 
function isBinary(object) {
  return NodeBuffer && NodeBuffer.isBuffer(object);
}
 
module.exports = new Type('tag:yaml.org,2002:binary', {
  kind: 'scalar',
  resolve: resolveYamlBinary,
  construct: constructYamlBinary,
  predicate: isBinary,
  represent: representYamlBinary
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/bool.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/bool.js

Statements: 64.29% (9 / 14)      Branches: 52.63% (10 / 19)      Functions: 33.33% (2 / 6)      Lines: 64.29% (9 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39    1   1 95       95   95       1 1         1       1                          
'use strict';
 
var Type = require('../type');
 
function resolveYamlBoolean(data) {
  Iif (null === data) {
    return false;
  }
 
  var max = data.length;
 
  return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
         (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
}
 
function constructYamlBoolean(data) {
  return data === 'true' ||
         data === 'True' ||
         data === 'TRUE';
}
 
function isBoolean(object) {
  return '[object Boolean]' === Object.prototype.toString.call(object);
}
 
module.exports = new Type('tag:yaml.org,2002:bool', {
  kind: 'scalar',
  resolve: resolveYamlBoolean,
  construct: constructYamlBoolean,
  predicate: isBoolean,
  represent: {
    lowercase: function (object) { return object ? 'true' : 'false'; },
    uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
    camelcase: function (object) { return object ? 'True' : 'False'; }
  },
  defaultStyle: 'lowercase'
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/float.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/float.js

Statements: 22.64% (12 / 53)      Branches: 5.56% (2 / 36)      Functions: 16.67% (1 / 6)      Lines: 22.64% (12 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110    1 1   1             1 94       94   94 94         1                                                                       1                                                                   1         1                  
'use strict';
 
var common = require('../common');
var Type   = require('../type');
 
var YAML_FLOAT_PATTERN = new RegExp(
  '^(?:[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+][0-9]+)?' +
  '|\\.[0-9_]+(?:[eE][-+][0-9]+)?' +
  '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' +
  '|[-+]?\\.(?:inf|Inf|INF)' +
  '|\\.(?:nan|NaN|NAN))$');
 
function resolveYamlFloat(data) {
  Iif (null === data) {
    return false;
  }
 
  var value, sign, base, digits;
 
  Eif (!YAML_FLOAT_PATTERN.test(data)) {
    return false;
  }
  return true;
}
 
function constructYamlFloat(data) {
  var value, sign, base, digits;
 
  value  = data.replace(/_/g, '').toLowerCase();
  sign   = '-' === value[0] ? -1 : 1;
  digits = [];
 
  if (0 <= '+-'.indexOf(value[0])) {
    value = value.slice(1);
  }
 
  if ('.inf' === value) {
    return (1 === sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
 
  } else if ('.nan' === value) {
    return NaN;
 
  } else if (0 <= value.indexOf(':')) {
    value.split(':').forEach(function (v) {
      digits.unshift(parseFloat(v, 10));
    });
 
    value = 0.0;
    base = 1;
 
    digits.forEach(function (d) {
      value += d * base;
      base *= 60;
    });
 
    return sign * value;
 
  }
  return sign * parseFloat(value, 10);
}
 
function representYamlFloat(object, style) {
  if (isNaN(object)) {
    switch (style) {
    case 'lowercase':
      return '.nan';
    case 'uppercase':
      return '.NAN';
    case 'camelcase':
      return '.NaN';
    }
  } else if (Number.POSITIVE_INFINITY === object) {
    switch (style) {
    case 'lowercase':
      return '.inf';
    case 'uppercase':
      return '.INF';
    case 'camelcase':
      return '.Inf';
    }
  } else if (Number.NEGATIVE_INFINITY === object) {
    switch (style) {
    case 'lowercase':
      return '-.inf';
    case 'uppercase':
      return '-.INF';
    case 'camelcase':
      return '-.Inf';
    }
  } else if (common.isNegativeZero(object)) {
    return '-0.0';
  }
  return object.toString(10);
}
 
function isFloat(object) {
  return ('[object Number]' === Object.prototype.toString.call(object)) &&
         (0 !== object % 1 || common.isNegativeZero(object));
}
 
module.exports = new Type('tag:yaml.org,2002:float', {
  kind: 'scalar',
  resolve: resolveYamlFloat,
  construct: constructYamlFloat,
  predicate: isFloat,
  represent: representYamlFloat,
  defaultStyle: 'lowercase'
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/int.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/int.js

Statements: 23.47% (23 / 98)      Branches: 16.9% (12 / 71)      Functions: 16.67% (2 / 12)      Lines: 26.14% (23 / 88)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185    1 1   1           1       1 95     1 94       94         94   94     94       94                                                                                                       94 95 95 95 95 94   1                       1                                                                                                   1         1                                        
'use strict';
 
var common = require('../common');
var Type   = require('../type');
 
function isHexCode(c) {
  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
         ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
         ((0x61/* a */ <= c) && (c <= 0x66/* f */));
}
 
function isOctCode(c) {
  return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
}
 
function isDecCode(c) {
  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
}
 
function resolveYamlInteger(data) {
  Iif (null === data) {
    return false;
  }
 
  var max = data.length,
      index = 0,
      hasDigits = false,
      ch;
 
  Iif (!max) { return false; }
 
  ch = data[index];
 
  // sign
  Iif (ch === '-' || ch === '+') {
    ch = data[++index];
  }
 
  Iif (ch === '0') {
    // 0
    if (index + 1 === max) { return true; }
    ch = data[++index];
 
    // base 2, base 8, base 16
 
    if (ch === 'b') {
      // base 2
      index++;
 
      for (; index < max; index++) {
        ch = data[index];
        if (ch === '_') { continue; }
        if (ch !== '0' && ch !== '1') {
          return false;
        }
        hasDigits = true;
      }
      return hasDigits;
    }
 
 
    if (ch === 'x') {
      // base 16
      index++;
 
      for (; index < max; index++) {
        ch = data[index];
        if (ch === '_') { continue; }
        if (!isHexCode(data.charCodeAt(index))) {
          return false;
        }
        hasDigits = true;
      }
      return hasDigits;
    }
 
    // base 8
    for (; index < max; index++) {
      ch = data[index];
      if (ch === '_') { continue; }
      if (!isOctCode(data.charCodeAt(index))) {
        return false;
      }
      hasDigits = true;
    }
    return hasDigits;
  }
 
  // base 10 (except 0) or base 60
 
  for (; index < max; index++) {
    ch = data[index];
    Iif (ch === '_') { continue; }
    Iif (ch === ':') { break; }
    if (!isDecCode(data.charCodeAt(index))) {
      return false;
    }
    hasDigits = true;
  }
 
  if (!hasDigits) { return false; }
 
  // if !base60 - done;
  if (ch !== ':') { return true; }
 
  // base60 almost not used, no needs to optimize
  return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}
 
function constructYamlInteger(data) {
  var value = data, sign = 1, ch, base, digits = [];
 
  if (value.indexOf('_') !== -1) {
    value = value.replace(/_/g, '');
  }
 
  ch = value[0];
 
  if (ch === '-' || ch === '+') {
    if (ch === '-') { sign = -1; }
    value = value.slice(1);
    ch = value[0];
  }
 
  if ('0' === value) {
    return 0;
  }
 
  if (ch === '0') {
    if (value[1] === 'b') {
      return sign * parseInt(value.slice(2), 2);
    }
    if (value[1] === 'x') {
      return sign * parseInt(value, 16);
    }
    return sign * parseInt(value, 8);
 
  }
 
  if (value.indexOf(':') !== -1) {
    value.split(':').forEach(function (v) {
      digits.unshift(parseInt(v, 10));
    });
 
    value = 0;
    base = 1;
 
    digits.forEach(function (d) {
      value += (d * base);
      base *= 60;
    });
 
    return sign * value;
 
  }
 
  return sign * parseInt(value, 10);
}
 
function isInteger(object) {
  return ('[object Number]' === Object.prototype.toString.call(object)) &&
         (0 === object % 1 && !common.isNegativeZero(object));
}
 
module.exports = new Type('tag:yaml.org,2002:int', {
  kind: 'scalar',
  resolve: resolveYamlInteger,
  construct: constructYamlInteger,
  predicate: isInteger,
  represent: {
    binary:      function (object) { return '0b' + object.toString(2); },
    octal:       function (object) { return '0'  + object.toString(8); },
    decimal:     function (object) { return        object.toString(10); },
    hexadecimal: function (object) { return '0x' + object.toString(16).toUpperCase(); }
  },
  defaultStyle: 'decimal',
  styleAliases: {
    binary:      [ 2,  'bin' ],
    octal:       [ 8,  'oct' ],
    decimal:     [ 10, 'dec' ],
    hexadecimal: [ 16, 'hex' ]
  }
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/map.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/map.js

Statements: 66.67% (2 / 3)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10    1   1          
'use strict';
 
var Type = require('../type');
 
module.exports = new Type('tag:yaml.org,2002:map', {
  kind: 'mapping',
  construct: function (data) { return null !== data ? data : {}; }
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/merge.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/merge.js

Statements: 100% (4 / 4)      Branches: 100% (2 / 2)      Functions: 100% (1 / 1)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14    1   1 94     1          
'use strict';
 
var Type = require('../type');
 
function resolveYamlMerge(data) {
  return '<<' === data || null === data;
}
 
module.exports = new Type('tag:yaml.org,2002:merge', {
  kind: 'scalar',
  resolve: resolveYamlMerge
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/null.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/null.js

Statements: 53.33% (8 / 15)      Branches: 75% (6 / 8)      Functions: 14.29% (1 / 7)      Lines: 53.33% (8 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38    1   1 95       95   95       1       1       1                            
'use strict';
 
var Type = require('../type');
 
function resolveYamlNull(data) {
  Iif (null === data) {
    return true;
  }
 
  var max = data.length;
 
  return (max === 1 && data === '~') ||
         (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
}
 
function constructYamlNull() {
  return null;
}
 
function isNull(object) {
  return null === object;
}
 
module.exports = new Type('tag:yaml.org,2002:null', {
  kind: 'scalar',
  resolve: resolveYamlNull,
  construct: constructYamlNull,
  predicate: isNull,
  represent: {
    canonical: function () { return '~';    },
    lowercase: function () { return 'null'; },
    uppercase: function () { return 'NULL'; },
    camelcase: function () { return 'Null'; }
  },
  defaultStyle: 'lowercase'
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/omap.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/omap.js

Statements: 23.08% (6 / 26)      Branches: 0% (0 / 14)      Functions: 0% (0 / 2)      Lines: 23.08% (6 / 26)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58    1   1 1   1                                                                               1       1            
'use strict';
 
var Type = require('../type');
 
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _toString       = Object.prototype.toString;
 
function resolveYamlOmap(data) {
  if (null === data) {
    return true;
  }
 
  var objectKeys = [], index, length, pair, pairKey, pairHasKey,
      object = data;
 
  for (index = 0, length = object.length; index < length; index += 1) {
    pair = object[index];
    pairHasKey = false;
 
    if ('[object Object]' !== _toString.call(pair)) {
      return false;
    }
 
    for (pairKey in pair) {
      if (_hasOwnProperty.call(pair, pairKey)) {
        if (!pairHasKey) {
          pairHasKey = true;
        } else {
          return false;
        }
      }
    }
 
    if (!pairHasKey) {
      return false;
    }
 
    if (-1 === objectKeys.indexOf(pairKey)) {
      objectKeys.push(pairKey);
    } else {
      return false;
    }
  }
 
  return true;
}
 
function constructYamlOmap(data) {
  return null !== data ? data : [];
}
 
module.exports = new Type('tag:yaml.org,2002:omap', {
  kind: 'sequence',
  resolve: resolveYamlOmap,
  construct: constructYamlOmap
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/pairs.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/pairs.js

Statements: 18.52% (5 / 27)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 18.52% (5 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63    1   1   1                                                         1                                         1            
'use strict';
 
var Type = require('../type');
 
var _toString = Object.prototype.toString;
 
function resolveYamlPairs(data) {
  if (null === data) {
    return true;
  }
 
  var index, length, pair, keys, result,
      object = data;
 
  result = new Array(object.length);
 
  for (index = 0, length = object.length; index < length; index += 1) {
    pair = object[index];
 
    if ('[object Object]' !== _toString.call(pair)) {
      return false;
    }
 
    keys = Object.keys(pair);
 
    if (1 !== keys.length) {
      return false;
    }
 
    result[index] = [ keys[0], pair[keys[0]] ];
  }
 
  return true;
}
 
function constructYamlPairs(data) {
  if (null === data) {
    return [];
  }
 
  var index, length, pair, keys, result,
      object = data;
 
  result = new Array(object.length);
 
  for (index = 0, length = object.length; index < length; index += 1) {
    pair = object[index];
 
    keys = Object.keys(pair);
 
    result[index] = [ keys[0], pair[keys[0]] ];
  }
 
  return result;
}
 
module.exports = new Type('tag:yaml.org,2002:pairs', {
  kind: 'sequence',
  resolve: resolveYamlPairs,
  construct: constructYamlPairs
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/seq.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/seq.js

Statements: 66.67% (2 / 3)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10    1   1          
'use strict';
 
var Type = require('../type');
 
module.exports = new Type('tag:yaml.org,2002:seq', {
  kind: 'sequence',
  construct: function (data) { return null !== data ? data : []; }
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/set.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/set.js

Statements: 35.71% (5 / 14)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 35.71% (5 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35    1   1   1                                   1       1            
'use strict';
 
var Type = require('../type');
 
var _hasOwnProperty = Object.prototype.hasOwnProperty;
 
function resolveYamlSet(data) {
  if (null === data) {
    return true;
  }
 
  var key, object = data;
 
  for (key in object) {
    if (_hasOwnProperty.call(object, key)) {
      if (null !== object[key]) {
        return false;
      }
    }
  }
 
  return true;
}
 
function constructYamlSet(data) {
  return null !== data ? data : {};
}
 
module.exports = new Type('tag:yaml.org,2002:set', {
  kind: 'mapping',
  resolve: resolveYamlSet,
  construct: constructYamlSet
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/str.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/str.js

Statements: 66.67% (2 / 3)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6 7 8 9 10    1   1          
'use strict';
 
var Type = require('../type');
 
module.exports = new Type('tag:yaml.org,2002:str', {
  kind: 'scalar',
  construct: function (data) { return null !== data ? data : ''; }
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/timestamp.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/timestamp.js

Statements: 26.83% (11 / 41)      Branches: 11.11% (2 / 18)      Functions: 33.33% (1 / 3)      Lines: 26.83% (11 / 41)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100    1   1                       1 94       94     94   94 94           1                                                                                                           1       1                
'use strict';
 
var Type = require('../type');
 
var YAML_TIMESTAMP_REGEXP = new RegExp(
  '^([0-9][0-9][0-9][0-9])'          + // [1] year
  '-([0-9][0-9]?)'                   + // [2] month
  '-([0-9][0-9]?)'                   + // [3] day
  '(?:(?:[Tt]|[ \\t]+)'              + // ...
  '([0-9][0-9]?)'                    + // [4] hour
  ':([0-9][0-9])'                    + // [5] minute
  ':([0-9][0-9])'                    + // [6] second
  '(?:\\.([0-9]*))?'                 + // [7] fraction
  '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
  '(?::([0-9][0-9]))?))?)?$');         // [11] tz_minute
 
function resolveYamlTimestamp(data) {
  Iif (null === data) {
    return false;
  }
 
  var match, year, month, day, hour, minute, second, fraction = 0,
      delta = null, tz_hour, tz_minute, date;
 
  match = YAML_TIMESTAMP_REGEXP.exec(data);
 
  Eif (null === match) {
    return false;
  }
 
  return true;
}
 
function constructYamlTimestamp(data) {
  var match, year, month, day, hour, minute, second, fraction = 0,
      delta = null, tz_hour, tz_minute, date;
 
  match = YAML_TIMESTAMP_REGEXP.exec(data);
 
  if (null === match) {
    throw new Error('Date resolve error');
  }
 
  // match: [1] year [2] month [3] day
 
  year = +(match[1]);
  month = +(match[2]) - 1; // JS month starts with 0
  day = +(match[3]);
 
  if (!match[4]) { // no hour
    return new Date(Date.UTC(year, month, day));
  }
 
  // match: [4] hour [5] minute [6] second [7] fraction
 
  hour = +(match[4]);
  minute = +(match[5]);
  second = +(match[6]);
 
  if (match[7]) {
    fraction = match[7].slice(0, 3);
    while (fraction.length < 3) { // milli-seconds
      fraction += '0';
    }
    fraction = +fraction;
  }
 
  // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute
 
  if (match[9]) {
    tz_hour = +(match[10]);
    tz_minute = +(match[11] || 0);
    delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
    if ('-' === match[9]) {
      delta = -delta;
    }
  }
 
  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
 
  if (delta) {
    date.setTime(date.getTime() - delta);
  }
 
  return date;
}
 
function representYamlTimestamp(object /*, style*/) {
  return object.toISOString();
}
 
module.exports = new Type('tag:yaml.org,2002:timestamp', {
  kind: 'scalar',
  resolve: resolveYamlTimestamp,
  construct: constructYamlTimestamp,
  instanceOf: Date,
  represent: representYamlTimestamp
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/

Statements: 27.63% (21 / 76)      Branches: 0% (0 / 38)      Functions: 0% (0 / 13)      Lines: 28.77% (21 / 73)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/
File Statements Branches Functions Lines
function.js 32.14% (9 / 28) 0% (0 / 16) 0% (0 / 5) 33.33% (9 / 27)
regexp.js 15.79% (6 / 38) 0% (0 / 22) 0% (0 / 4) 16.67% (6 / 36)
undefined.js 60% (6 / 10) 100% (0 / 0) 0% (0 / 4) 60% (6 / 10)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/function.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/function.js

Statements: 32.14% (9 / 28)      Branches: 0% (0 / 16)      Functions: 0% (0 / 5)      Lines: 33.33% (9 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88    1                 1 1           1   1                                               1                                                     1       1       1                
'use strict';
 
var esprima;
 
// Browserified version does not have esprima
//
// 1. For node.js just require module as deps
// 2. For browser try to require mudule via external AMD system.
//    If not found - try to fallback to window.esprima. If not
//    found too - then fail to parse.
//
try {
  esprima = require('esprima');
} catch (_) {
  /*global window */
  if (typeof window !== 'undefined') { esprima = window.esprima; }
}
 
var Type = require('../../type');
 
function resolveJavascriptFunction(data) {
  if (null === data) {
    return false;
  }
 
  try {
    var source = '(' + data + ')',
        ast    = esprima.parse(source, { range: true }),
        params = [],
        body;
 
    if ('Program'             !== ast.type         ||
        1                     !== ast.body.length  ||
        'ExpressionStatement' !== ast.body[0].type ||
        'FunctionExpression'  !== ast.body[0].expression.type) {
      return false;
    }
 
    return true;
  } catch (err) {
    return false;
  }
}
 
function constructJavascriptFunction(data) {
  /*jslint evil:true*/
 
  var source = '(' + data + ')',
      ast    = esprima.parse(source, { range: true }),
      params = [],
      body;
 
  if ('Program'             !== ast.type         ||
      1                     !== ast.body.length  ||
      'ExpressionStatement' !== ast.body[0].type ||
      'FunctionExpression'  !== ast.body[0].expression.type) {
    throw new Error('Failed to resolve function');
  }
 
  ast.body[0].expression.params.forEach(function (param) {
    params.push(param.name);
  });
 
  body = ast.body[0].expression.body.range;
 
  // Esprima's ranges include the first '{' and the last '}' characters on
  // function expressions. So cut them out.
  /*eslint-disable no-new-func*/
  return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
 
function representJavascriptFunction(object /*, style*/) {
  return object.toString();
}
 
function isFunction(object) {
  return '[object Function]' === Object.prototype.toString.call(object);
}
 
module.exports = new Type('tag:yaml.org,2002:js/function', {
  kind: 'scalar',
  resolve: resolveJavascriptFunction,
  construct: constructJavascriptFunction,
  predicate: isFunction,
  represent: representJavascriptFunction
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js

Statements: 15.79% (6 / 38)      Branches: 0% (0 / 22)      Functions: 0% (0 / 4)      Lines: 16.67% (6 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86    1   1                                                                     1                               1                                   1       1                
'use strict';
 
var Type = require('../../type');
 
function resolveJavascriptRegExp(data) {
  if (null === data) {
    return false;
  }
 
  if (0 === data.length) {
    return false;
  }
 
  var regexp = data,
      tail   = /\/([gim]*)$/.exec(data),
      modifiers = '';
 
  // if regexp starts with '/' it can have modifiers and must be properly closed
  // `/foo/gim` - modifiers tail can be maximum 3 chars
  if ('/' === regexp[0]) {
    if (tail) {
      modifiers = tail[1];
    }
 
    if (modifiers.length > 3) { return false; }
    // if expression starts with /, is should be properly terminated
    if (regexp[regexp.length - modifiers.length - 1] !== '/') { return false; }
 
    regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
  }
 
  try {
    var dummy = new RegExp(regexp, modifiers);
    return true;
  } catch (error) {
    return false;
  }
}
 
function constructJavascriptRegExp(data) {
  var regexp = data,
      tail   = /\/([gim]*)$/.exec(data),
      modifiers = '';
 
  // `/foo/gim` - tail can be maximum 4 chars
  if ('/' === regexp[0]) {
    if (tail) {
      modifiers = tail[1];
    }
    regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
  }
 
  return new RegExp(regexp, modifiers);
}
 
function representJavascriptRegExp(object /*, style*/) {
  var result = '/' + object.source + '/';
 
  if (object.global) {
    result += 'g';
  }
 
  if (object.multiline) {
    result += 'm';
  }
 
  if (object.ignoreCase) {
    result += 'i';
  }
 
  return result;
}
 
function isRegExp(object) {
  return '[object RegExp]' === Object.prototype.toString.call(object);
}
 
module.exports = new Type('tag:yaml.org,2002:js/regexp', {
  kind: 'scalar',
  resolve: resolveJavascriptRegExp,
  construct: constructJavascriptRegExp,
  predicate: isRegExp,
  represent: representJavascriptRegExp
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js

Statements: 60% (6 / 10)      Branches: 100% (0 / 0)      Functions: 0% (0 / 4)      Lines: 60% (6 / 10)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30    1   1       1         1       1       1                
'use strict';
 
var Type = require('../../type');
 
function resolveJavascriptUndefined() {
  return true;
}
 
function constructJavascriptUndefined() {
  /*eslint-disable no-undefined*/
  return undefined;
}
 
function representJavascriptUndefined() {
  return '';
}
 
function isUndefined(object) {
  return 'undefined' === typeof object;
}
 
module.exports = new Type('tag:yaml.org,2002:js/undefined', {
  kind: 'scalar',
  resolve: resolveJavascriptUndefined,
  construct: constructJavascriptUndefined,
  predicate: isUndefined,
  represent: representJavascriptUndefined
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/node_modules/esprima/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/node_modules/esprima/

Statements: 7.55% (205 / 2714)      Branches: 1.98% (31 / 1567)      Functions: 1.8% (4 / 222)      Lines: 7.55% (205 / 2714)      Ignored: 16 statements, 1 function, 25 branches     

All files » node-npmtest-sinopia/sinopia/node_modules/js-yaml/node_modules/esprima/
File Statements Branches Functions Lines
esprima.js 7.55% (205 / 2714) 1.98% (31 / 1567) 1.8% (4 / 222) 7.55% (205 / 2714)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/node_modules/esprima/esprima.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/js-yaml/node_modules/esprima/esprima.js

Statements: 7.55% (205 / 2714)      Branches: 1.98% (31 / 1567)      Functions: 1.8% (4 / 222)      Lines: 7.55% (205 / 2714)      Ignored: 16 statements, 1 function, 25 branches     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323                                                                  1             1 1 1 1   1         1                                                         1                         1 1 1 1 1 1 1 1 1 1 1     1                   1                                                                                                                                 1         1                                                                                               1                   1     1       1       1       1       1                                                 1             1           1               1                     1                           1                                 1           1                                                                     1                                               1                                                                                     1                                                                                                               1                                                                                                                   1                             1                                                               1                                                                                         1                                         1                                                                     1                                                                                                                                                                                                       1                                                       1                                                                       1                                                                             1                                   1                                                                                                                                                                     1                                                                                                                                                                                             1                                                                                                                                                                                                                                                   1                                                                                     1                                                                                             1                                                                                         1                                                                             1                                         1   1 1 1 1 1         1                       1             1                                                                                                                             1                                                                                                                       1                                                                       1                                         1                                 1         1         1               1                 1                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1             1 1             1                     1                           1         1   1 1                           1                                                                 1       1                       1                         1                                         1                 1           1             1           1                                         1                                                                                                       1                                   1                             1                                                           1                                         1                                 1                     1                         1                                                                     1                                     1                 1                                                             1                                         1                                                                                                                 1                     1                                                                       1                                   1                                                                       1                         1                                   1                                                                                                                                                                                             1                                                                                                                                               1                                       1                       1           1                       1                       1                                                                                         1                                                                               1                                                       1                                                                                 1                                                                                                                                                             1                                                                                                               1                                               1             1                                                     1                                                                                                               1                                                 1                                                                                             1                                               1                                                   1                       1                           1                               1                                       1                           1                       1                                             1                           1                         1                                               1             1               1                                                 1                                                     1                                         1                                                                                                                                                                                                                 1                                                                                       1                                                                                       1                                                                       1                                           1                                             1                                                                                             1                                   1                                           1                                                 1                   1                                                                                                                                                                         1                                                                                                                           1                                                   1                                                     1                                                                         1                                                                                       1                                                                                             1                                                                                                                   1                                       1                                             1                 1                                 1                                                                                                 1                                                                             1                                 1                                 1                         1                         1                 1                           1                                                                                                       1                                                               1             1                   1                                                     1                                                                                                                                                                                 1                                                                                                                                                                       1   1   1       1 1   1 1     1 62 62       1 1     1            
/*
  Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com>
  Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
  Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
  Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
 
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
 
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
 
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
(function (root, factory) {
    'use strict';
 
    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
 
    /* istanbul ignore next */
    Iif (typeof define === 'function' && define.amd) {
        define(['exports'], factory);
    } else Eif (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.esprima = {}));
    }
}(this, function (exports) {
    'use strict';
 
    var Token,
        TokenName,
        FnExprTokens,
        Syntax,
        PlaceHolders,
        Messages,
        Regex,
        source,
        strict,
        sourceType,
        index,
        lineNumber,
        lineStart,
        hasLineTerminator,
        lastIndex,
        lastLineNumber,
        lastLineStart,
        startIndex,
        startLineNumber,
        startLineStart,
        scanning,
        length,
        lookahead,
        state,
        extra,
        isBindingElement,
        isAssignmentTarget,
        firstCoverInitializedNameError;
 
    Token = {
        BooleanLiteral: 1,
        EOF: 2,
        Identifier: 3,
        Keyword: 4,
        NullLiteral: 5,
        NumericLiteral: 6,
        Punctuator: 7,
        StringLiteral: 8,
        RegularExpression: 9,
        Template: 10
    };
 
    TokenName = {};
    TokenName[Token.BooleanLiteral] = 'Boolean';
    TokenName[Token.EOF] = '<end>';
    TokenName[Token.Identifier] = 'Identifier';
    TokenName[Token.Keyword] = 'Keyword';
    TokenName[Token.NullLiteral] = 'Null';
    TokenName[Token.NumericLiteral] = 'Numeric';
    TokenName[Token.Punctuator] = 'Punctuator';
    TokenName[Token.StringLiteral] = 'String';
    TokenName[Token.RegularExpression] = 'RegularExpression';
    TokenName[Token.Template] = 'Template';
 
    // A function following one of those tokens is an expression.
    FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
                    'return', 'case', 'delete', 'throw', 'void',
                    // assignment operators
                    '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
                    '&=', '|=', '^=', ',',
                    // binary/unary operators
                    '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
                    '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
                    '<=', '<', '>', '!=', '!=='];
 
    Syntax = {
        AssignmentExpression: 'AssignmentExpression',
        AssignmentPattern: 'AssignmentPattern',
        ArrayExpression: 'ArrayExpression',
        ArrayPattern: 'ArrayPattern',
        ArrowFunctionExpression: 'ArrowFunctionExpression',
        BlockStatement: 'BlockStatement',
        BinaryExpression: 'BinaryExpression',
        BreakStatement: 'BreakStatement',
        CallExpression: 'CallExpression',
        CatchClause: 'CatchClause',
        ClassBody: 'ClassBody',
        ClassDeclaration: 'ClassDeclaration',
        ClassExpression: 'ClassExpression',
        ConditionalExpression: 'ConditionalExpression',
        ContinueStatement: 'ContinueStatement',
        DoWhileStatement: 'DoWhileStatement',
        DebuggerStatement: 'DebuggerStatement',
        EmptyStatement: 'EmptyStatement',
        ExportAllDeclaration: 'ExportAllDeclaration',
        ExportDefaultDeclaration: 'ExportDefaultDeclaration',
        ExportNamedDeclaration: 'ExportNamedDeclaration',
        ExportSpecifier: 'ExportSpecifier',
        ExpressionStatement: 'ExpressionStatement',
        ForStatement: 'ForStatement',
        ForInStatement: 'ForInStatement',
        FunctionDeclaration: 'FunctionDeclaration',
        FunctionExpression: 'FunctionExpression',
        Identifier: 'Identifier',
        IfStatement: 'IfStatement',
        ImportDeclaration: 'ImportDeclaration',
        ImportDefaultSpecifier: 'ImportDefaultSpecifier',
        ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
        ImportSpecifier: 'ImportSpecifier',
        Literal: 'Literal',
        LabeledStatement: 'LabeledStatement',
        LogicalExpression: 'LogicalExpression',
        MemberExpression: 'MemberExpression',
        MethodDefinition: 'MethodDefinition',
        NewExpression: 'NewExpression',
        ObjectExpression: 'ObjectExpression',
        ObjectPattern: 'ObjectPattern',
        Program: 'Program',
        Property: 'Property',
        RestElement: 'RestElement',
        ReturnStatement: 'ReturnStatement',
        SequenceExpression: 'SequenceExpression',
        SpreadElement: 'SpreadElement',
        Super: 'Super',
        SwitchCase: 'SwitchCase',
        SwitchStatement: 'SwitchStatement',
        TaggedTemplateExpression: 'TaggedTemplateExpression',
        TemplateElement: 'TemplateElement',
        TemplateLiteral: 'TemplateLiteral',
        ThisExpression: 'ThisExpression',
        ThrowStatement: 'ThrowStatement',
        TryStatement: 'TryStatement',
        UnaryExpression: 'UnaryExpression',
        UpdateExpression: 'UpdateExpression',
        VariableDeclaration: 'VariableDeclaration',
        VariableDeclarator: 'VariableDeclarator',
        WhileStatement: 'WhileStatement',
        WithStatement: 'WithStatement'
    };
 
    PlaceHolders = {
        ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder'
    };
 
    // Error messages should be identical to V8.
    Messages = {
        UnexpectedToken: 'Unexpected token %0',
        UnexpectedNumber: 'Unexpected number',
        UnexpectedString: 'Unexpected string',
        UnexpectedIdentifier: 'Unexpected identifier',
        UnexpectedReserved: 'Unexpected reserved word',
        UnexpectedTemplate: 'Unexpected quasi %0',
        UnexpectedEOS: 'Unexpected end of input',
        NewlineAfterThrow: 'Illegal newline after throw',
        InvalidRegExp: 'Invalid regular expression',
        UnterminatedRegExp: 'Invalid regular expression: missing /',
        InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
        InvalidLHSInForIn: 'Invalid left-hand side in for-in',
        MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
        NoCatchOrFinally: 'Missing catch or finally after try',
        UnknownLabel: 'Undefined label \'%0\'',
        Redeclaration: '%0 \'%1\' has already been declared',
        IllegalContinue: 'Illegal continue statement',
        IllegalBreak: 'Illegal break statement',
        IllegalReturn: 'Illegal return statement',
        StrictModeWith: 'Strict mode code may not include a with statement',
        StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
        StrictVarName: 'Variable name may not be eval or arguments in strict mode',
        StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
        StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
        StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
        StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
        StrictDelete: 'Delete of an unqualified identifier in strict mode.',
        StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
        StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
        StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
        StrictReservedWord: 'Use of future reserved word in strict mode',
        TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
        ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
        DefaultRestParameter: 'Unexpected token =',
        ObjectPatternAsRestParameter: 'Unexpected token {',
        DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
        ConstructorSpecialMethod: 'Class constructor may not be an accessor',
        DuplicateConstructor: 'A class may only have one constructor',
        StaticPrototype: 'Classes may not have static property named prototype',
        MissingFromClause: 'Unexpected token',
        NoAsAfterImportNamespace: 'Unexpected token',
        InvalidModuleSpecifier: 'Unexpected token',
        IllegalImportDeclaration: 'Unexpected token',
        IllegalExportDeclaration: 'Unexpected token'
    };
 
    // See also tools/generate-unicode-regex.py.
    Regex = {
        NonAsciiIdentifierStart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'),
        NonAsciiIdentifierPart: new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]')
    };
 
    // Ensure the condition is true, otherwise throw an error.
    // This is only to have a better contract semantic, i.e. another safety net
    // to catch a logic error. The condition shall be fulfilled in normal case.
    // Do NOT use this to enforce a certain condition on any user input.
 
    function assert(condition, message) {
        /* istanbul ignore if */
        if (!condition) {
            throw new Error('ASSERT: ' + message);
        }
    }
 
    function isDecimalDigit(ch) {
        return (ch >= 0x30 && ch <= 0x39);   // 0..9
    }
 
    function isHexDigit(ch) {
        return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
    }
 
    function isOctalDigit(ch) {
        return '01234567'.indexOf(ch) >= 0;
    }
 
    function octalToDecimal(ch) {
        // \0 is not octal escape sequence
        var octal = (ch !== '0'), code = '01234567'.indexOf(ch);
 
        if (index < length && isOctalDigit(source[index])) {
            octal = true;
            code = code * 8 + '01234567'.indexOf(source[index++]);
 
            // 3 digits are only allowed when string starts
            // with 0, 1, 2, 3
            if ('0123'.indexOf(ch) >= 0 &&
                    index < length &&
                    isOctalDigit(source[index])) {
                code = code * 8 + '01234567'.indexOf(source[index++]);
            }
        }
 
        return {
            code: code,
            octal: octal
        };
    }
 
    // 7.2 White Space
 
    function isWhiteSpace(ch) {
        return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) ||
            (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0);
    }
 
    // 7.3 Line Terminators
 
    function isLineTerminator(ch) {
        return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029);
    }
 
    // 7.6 Identifier Names and Identifiers
 
    function isIdentifierStart(ch) {
        return (ch === 0x24) || (ch === 0x5F) ||  // $ (dollar) and _ (underscore)
            (ch >= 0x41 && ch <= 0x5A) ||         // A..Z
            (ch >= 0x61 && ch <= 0x7A) ||         // a..z
            (ch === 0x5C) ||                      // \ (backslash)
            ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
    }
 
    function isIdentifierPart(ch) {
        return (ch === 0x24) || (ch === 0x5F) ||  // $ (dollar) and _ (underscore)
            (ch >= 0x41 && ch <= 0x5A) ||         // A..Z
            (ch >= 0x61 && ch <= 0x7A) ||         // a..z
            (ch >= 0x30 && ch <= 0x39) ||         // 0..9
            (ch === 0x5C) ||                      // \ (backslash)
            ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
    }
 
    // 7.6.1.2 Future Reserved Words
 
    function isFutureReservedWord(id) {
        switch (id) {
        case 'enum':
        case 'export':
        case 'import':
        case 'super':
            return true;
        default:
            return false;
        }
    }
 
    // 11.6.2.2 Future Reserved Words
 
    function isStrictModeReservedWord(id) {
        switch (id) {
        case 'implements':
        case 'interface':
        case 'package':
        case 'private':
        case 'protected':
        case 'public':
        case 'static':
        case 'yield':
        case 'let':
            return true;
        default:
            return false;
        }
    }
 
    function isRestrictedWord(id) {
        return id === 'eval' || id === 'arguments';
    }
 
    // 7.6.1.1 Keywords
 
    function isKeyword(id) {
 
        // 'const' is specialized as Keyword in V8.
        // 'yield' and 'let' are for compatibility with SpiderMonkey and ES.next.
        // Some others are from future reserved words.
 
        switch (id.length) {
        case 2:
            return (id === 'if') || (id === 'in') || (id === 'do');
        case 3:
            return (id === 'var') || (id === 'for') || (id === 'new') ||
                (id === 'try') || (id === 'let');
        case 4:
            return (id === 'this') || (id === 'else') || (id === 'case') ||
                (id === 'void') || (id === 'with') || (id === 'enum');
        case 5:
            return (id === 'while') || (id === 'break') || (id === 'catch') ||
                (id === 'throw') || (id === 'const') || (id === 'yield') ||
                (id === 'class') || (id === 'super');
        case 6:
            return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
                (id === 'switch') || (id === 'export') || (id === 'import');
        case 7:
            return (id === 'default') || (id === 'finally') || (id === 'extends');
        case 8:
            return (id === 'function') || (id === 'continue') || (id === 'debugger');
        case 10:
            return (id === 'instanceof');
        default:
            return false;
        }
    }
 
    // 7.4 Comments
 
    function addComment(type, value, start, end, loc) {
        var comment;
 
        assert(typeof start === 'number', 'Comment must have valid position');
 
        state.lastCommentStart = start;
 
        comment = {
            type: type,
            value: value
        };
        if (extra.range) {
            comment.range = [start, end];
        }
        if (extra.loc) {
            comment.loc = loc;
        }
        extra.comments.push(comment);
        if (extra.attachComment) {
            extra.leadingComments.push(comment);
            extra.trailingComments.push(comment);
        }
    }
 
    function skipSingleLineComment(offset) {
        var start, loc, ch, comment;
 
        start = index - offset;
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart - offset
            }
        };
 
        while (index < length) {
            ch = source.charCodeAt(index);
            ++index;
            if (isLineTerminator(ch)) {
                hasLineTerminator = true;
                if (extra.comments) {
                    comment = source.slice(start + offset, index - 1);
                    loc.end = {
                        line: lineNumber,
                        column: index - lineStart - 1
                    };
                    addComment('Line', comment, start, index - 1, loc);
                }
                if (ch === 13 && source.charCodeAt(index) === 10) {
                    ++index;
                }
                ++lineNumber;
                lineStart = index;
                return;
            }
        }
 
        if (extra.comments) {
            comment = source.slice(start + offset, index);
            loc.end = {
                line: lineNumber,
                column: index - lineStart
            };
            addComment('Line', comment, start, index, loc);
        }
    }
 
    function skipMultiLineComment() {
        var start, loc, ch, comment;
 
        if (extra.comments) {
            start = index - 2;
            loc = {
                start: {
                    line: lineNumber,
                    column: index - lineStart - 2
                }
            };
        }
 
        while (index < length) {
            ch = source.charCodeAt(index);
            if (isLineTerminator(ch)) {
                if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) {
                    ++index;
                }
                hasLineTerminator = true;
                ++lineNumber;
                ++index;
                lineStart = index;
            } else if (ch === 0x2A) {
                // Block comment ends with '*/'.
                if (source.charCodeAt(index + 1) === 0x2F) {
                    ++index;
                    ++index;
                    if (extra.comments) {
                        comment = source.slice(start + 2, index - 2);
                        loc.end = {
                            line: lineNumber,
                            column: index - lineStart
                        };
                        addComment('Block', comment, start, index, loc);
                    }
                    return;
                }
                ++index;
            } else {
                ++index;
            }
        }
 
        // Ran off the end of the file - the whole thing is a comment
        if (extra.comments) {
            loc.end = {
                line: lineNumber,
                column: index - lineStart
            };
            comment = source.slice(start + 2, index);
            addComment('Block', comment, start, index, loc);
        }
        tolerateUnexpectedToken();
    }
 
    function skipComment() {
        var ch, start;
        hasLineTerminator = false;
 
        start = (index === 0);
        while (index < length) {
            ch = source.charCodeAt(index);
 
            if (isWhiteSpace(ch)) {
                ++index;
            } else if (isLineTerminator(ch)) {
                hasLineTerminator = true;
                ++index;
                if (ch === 0x0D && source.charCodeAt(index) === 0x0A) {
                    ++index;
                }
                ++lineNumber;
                lineStart = index;
                start = true;
            } else if (ch === 0x2F) { // U+002F is '/'
                ch = source.charCodeAt(index + 1);
                if (ch === 0x2F) {
                    ++index;
                    ++index;
                    skipSingleLineComment(2);
                    start = true;
                } else if (ch === 0x2A) {  // U+002A is '*'
                    ++index;
                    ++index;
                    skipMultiLineComment();
                } else {
                    break;
                }
            } else if (start && ch === 0x2D) { // U+002D is '-'
                // U+003E is '>'
                if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) {
                    // '-->' is a single-line comment
                    index += 3;
                    skipSingleLineComment(3);
                } else {
                    break;
                }
            } else if (ch === 0x3C) { // U+003C is '<'
                if (source.slice(index + 1, index + 4) === '!--') {
                    ++index; // `<`
                    ++index; // `!`
                    ++index; // `-`
                    ++index; // `-`
                    skipSingleLineComment(4);
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    }
 
    function scanHexEscape(prefix) {
        var i, len, ch, code = 0;
 
        len = (prefix === 'u') ? 4 : 2;
        for (i = 0; i < len; ++i) {
            if (index < length && isHexDigit(source[index])) {
                ch = source[index++];
                code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
            } else {
                return '';
            }
        }
        return String.fromCharCode(code);
    }
 
    function scanUnicodeCodePointEscape() {
        var ch, code, cu1, cu2;
 
        ch = source[index];
        code = 0;
 
        // At least, one hex digit is required.
        if (ch === '}') {
            throwUnexpectedToken();
        }
 
        while (index < length) {
            ch = source[index++];
            if (!isHexDigit(ch)) {
                break;
            }
            code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
        }
 
        if (code > 0x10FFFF || ch !== '}') {
            throwUnexpectedToken();
        }
 
        // UTF-16 Encoding
        if (code <= 0xFFFF) {
            return String.fromCharCode(code);
        }
        cu1 = ((code - 0x10000) >> 10) + 0xD800;
        cu2 = ((code - 0x10000) & 1023) + 0xDC00;
        return String.fromCharCode(cu1, cu2);
    }
 
    function getEscapedIdentifier() {
        var ch, id;
 
        ch = source.charCodeAt(index++);
        id = String.fromCharCode(ch);
 
        // '\u' (U+005C, U+0075) denotes an escaped character.
        if (ch === 0x5C) {
            if (source.charCodeAt(index) !== 0x75) {
                throwUnexpectedToken();
            }
            ++index;
            ch = scanHexEscape('u');
            if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
                throwUnexpectedToken();
            }
            id = ch;
        }
 
        while (index < length) {
            ch = source.charCodeAt(index);
            if (!isIdentifierPart(ch)) {
                break;
            }
            ++index;
            id += String.fromCharCode(ch);
 
            // '\u' (U+005C, U+0075) denotes an escaped character.
            if (ch === 0x5C) {
                id = id.substr(0, id.length - 1);
                if (source.charCodeAt(index) !== 0x75) {
                    throwUnexpectedToken();
                }
                ++index;
                ch = scanHexEscape('u');
                if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
                    throwUnexpectedToken();
                }
                id += ch;
            }
        }
 
        return id;
    }
 
    function getIdentifier() {
        var start, ch;
 
        start = index++;
        while (index < length) {
            ch = source.charCodeAt(index);
            if (ch === 0x5C) {
                // Blackslash (U+005C) marks Unicode escape sequence.
                index = start;
                return getEscapedIdentifier();
            }
            if (isIdentifierPart(ch)) {
                ++index;
            } else {
                break;
            }
        }
 
        return source.slice(start, index);
    }
 
    function scanIdentifier() {
        var start, id, type;
 
        start = index;
 
        // Backslash (U+005C) starts an escaped character.
        id = (source.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier();
 
        // There is no keyword or literal with only one character.
        // Thus, it must be an identifier.
        if (id.length === 1) {
            type = Token.Identifier;
        } else if (isKeyword(id)) {
            type = Token.Keyword;
        } else if (id === 'null') {
            type = Token.NullLiteral;
        } else if (id === 'true' || id === 'false') {
            type = Token.BooleanLiteral;
        } else {
            type = Token.Identifier;
        }
 
        return {
            type: type,
            value: id,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }
 
 
    // 7.7 Punctuators
 
    function scanPunctuator() {
        var token, str;
 
        token = {
            type: Token.Punctuator,
            value: '',
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: index,
            end: index
        };
 
        // Check for most common single-character punctuators.
        str = source[index];
        switch (str) {
 
        case '(':
            if (extra.tokenize) {
                extra.openParenToken = extra.tokens.length;
            }
            ++index;
            break;
 
        case '{':
            if (extra.tokenize) {
                extra.openCurlyToken = extra.tokens.length;
            }
            state.curlyStack.push('{');
            ++index;
            break;
 
        case '.':
            ++index;
            if (source[index] === '.' && source[index + 1] === '.') {
                // Spread operator: ...
                index += 2;
                str = '...';
            }
            break;
 
        case '}':
            ++index;
            state.curlyStack.pop();
            break;
        case ')':
        case ';':
        case ',':
        case '[':
        case ']':
        case ':':
        case '?':
        case '~':
            ++index;
            break;
 
        default:
            // 4-character punctuator.
            str = source.substr(index, 4);
            if (str === '>>>=') {
                index += 4;
            } else {
 
                // 3-character punctuators.
                str = str.substr(0, 3);
                if (str === '===' || str === '!==' || str === '>>>' ||
                    str === '<<=' || str === '>>=') {
                    index += 3;
                } else {
 
                    // 2-character punctuators.
                    str = str.substr(0, 2);
                    if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
                        str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
                        str === '++' || str === '--' || str === '<<' || str === '>>' ||
                        str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
                        str === '<=' || str === '>=' || str === '=>') {
                        index += 2;
                    } else {
 
                        // 1-character punctuators.
                        str = source[index];
                        if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
                            ++index;
                        }
                    }
                }
            }
        }
 
        if (index === token.start) {
            throwUnexpectedToken();
        }
 
        token.end = index;
        token.value = str;
        return token;
    }
 
    // 7.8.3 Numeric Literals
 
    function scanHexLiteral(start) {
        var number = '';
 
        while (index < length) {
            if (!isHexDigit(source[index])) {
                break;
            }
            number += source[index++];
        }
 
        if (number.length === 0) {
            throwUnexpectedToken();
        }
 
        if (isIdentifierStart(source.charCodeAt(index))) {
            throwUnexpectedToken();
        }
 
        return {
            type: Token.NumericLiteral,
            value: parseInt('0x' + number, 16),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }
 
    function scanBinaryLiteral(start) {
        var ch, number;
 
        number = '';
 
        while (index < length) {
            ch = source[index];
            if (ch !== '0' && ch !== '1') {
                break;
            }
            number += source[index++];
        }
 
        if (number.length === 0) {
            // only 0b or 0B
            throwUnexpectedToken();
        }
 
        if (index < length) {
            ch = source.charCodeAt(index);
            /* istanbul ignore else */
            if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
                throwUnexpectedToken();
            }
        }
 
        return {
            type: Token.NumericLiteral,
            value: parseInt(number, 2),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }
 
    function scanOctalLiteral(prefix, start) {
        var number, octal;
 
        if (isOctalDigit(prefix)) {
            octal = true;
            number = '0' + source[index++];
        } else {
            octal = false;
            ++index;
            number = '';
        }
 
        while (index < length) {
            if (!isOctalDigit(source[index])) {
                break;
            }
            number += source[index++];
        }
 
        if (!octal && number.length === 0) {
            // only 0o or 0O
            throwUnexpectedToken();
        }
 
        if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
            throwUnexpectedToken();
        }
 
        return {
            type: Token.NumericLiteral,
            value: parseInt(number, 8),
            octal: octal,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }
 
    function isImplicitOctalLiteral() {
        var i, ch;
 
        // Implicit octal, unless there is a non-octal digit.
        // (Annex B.1.1 on Numeric Literals)
        for (i = index + 1; i < length; ++i) {
            ch = source[i];
            if (ch === '8' || ch === '9') {
                return false;
            }
            if (!isOctalDigit(ch)) {
                return true;
            }
        }
 
        return true;
    }
 
    function scanNumericLiteral() {
        var number, start, ch;
 
        ch = source[index];
        assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
            'Numeric literal must start with a decimal digit or a decimal point');
 
        start = index;
        number = '';
        if (ch !== '.') {
            number = source[index++];
            ch = source[index];
 
            // Hex number starts with '0x'.
            // Octal number starts with '0'.
            // Octal number in ES6 starts with '0o'.
            // Binary number in ES6 starts with '0b'.
            if (number === '0') {
                if (ch === 'x' || ch === 'X') {
                    ++index;
                    return scanHexLiteral(start);
                }
                if (ch === 'b' || ch === 'B') {
                    ++index;
                    return scanBinaryLiteral(start);
                }
                if (ch === 'o' || ch === 'O') {
                    return scanOctalLiteral(ch, start);
                }
 
                if (isOctalDigit(ch)) {
                    if (isImplicitOctalLiteral()) {
                        return scanOctalLiteral(ch, start);
                    }
                }
            }
 
            while (isDecimalDigit(source.charCodeAt(index))) {
                number += source[index++];
            }
            ch = source[index];
        }
 
        if (ch === '.') {
            number += source[index++];
            while (isDecimalDigit(source.charCodeAt(index))) {
                number += source[index++];
            }
            ch = source[index];
        }
 
        if (ch === 'e' || ch === 'E') {
            number += source[index++];
 
            ch = source[index];
            if (ch === '+' || ch === '-') {
                number += source[index++];
            }
            if (isDecimalDigit(source.charCodeAt(index))) {
                while (isDecimalDigit(source.charCodeAt(index))) {
                    number += source[index++];
                }
            } else {
                throwUnexpectedToken();
            }
        }
 
        if (isIdentifierStart(source.charCodeAt(index))) {
            throwUnexpectedToken();
        }
 
        return {
            type: Token.NumericLiteral,
            value: parseFloat(number),
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }
 
    // 7.8.4 String Literals
 
    function scanStringLiteral() {
        var str = '', quote, start, ch, unescaped, octToDec, octal = false;
 
        quote = source[index];
        assert((quote === '\'' || quote === '"'),
            'String literal must starts with a quote');
 
        start = index;
        ++index;
 
        while (index < length) {
            ch = source[index++];
 
            if (ch === quote) {
                quote = '';
                break;
            } else if (ch === '\\') {
                ch = source[index++];
                if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
                    switch (ch) {
                    case 'u':
                    case 'x':
                        if (source[index] === '{') {
                            ++index;
                            str += scanUnicodeCodePointEscape();
                        } else {
                            unescaped = scanHexEscape(ch);
                            if (!unescaped) {
                                throw throwUnexpectedToken();
                            }
                            str += unescaped;
                        }
                        break;
                    case 'n':
                        str += '\n';
                        break;
                    case 'r':
                        str += '\r';
                        break;
                    case 't':
                        str += '\t';
                        break;
                    case 'b':
                        str += '\b';
                        break;
                    case 'f':
                        str += '\f';
                        break;
                    case 'v':
                        str += '\x0B';
                        break;
                    case '8':
                    case '9':
                        throw throwUnexpectedToken();
 
                    default:
                        if (isOctalDigit(ch)) {
                            octToDec = octalToDecimal(ch);
 
                            octal = octToDec.octal || octal;
                            str += String.fromCharCode(octToDec.code);
                        } else {
                            str += ch;
                        }
                        break;
                    }
                } else {
                    ++lineNumber;
                    if (ch === '\r' && source[index] === '\n') {
                        ++index;
                    }
                    lineStart = index;
                }
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                break;
            } else {
                str += ch;
            }
        }
 
        if (quote !== '') {
            throwUnexpectedToken();
        }
 
        return {
            type: Token.StringLiteral,
            value: str,
            octal: octal,
            lineNumber: startLineNumber,
            lineStart: startLineStart,
            start: start,
            end: index
        };
    }
 
    function scanTemplate() {
        var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped;
 
        terminated = false;
        tail = false;
        start = index;
        head = (source[index] === '`');
        rawOffset = 2;
 
        ++index;
 
        while (index < length) {
            ch = source[index++];
            if (ch === '`') {
                rawOffset = 1;
                tail = true;
                terminated = true;
                break;
            } else if (ch === '$') {
                if (source[index] === '{') {
                    state.curlyStack.push('${');
                    ++index;
                    terminated = true;
                    break;
                }
                cooked += ch;
            } else if (ch === '\\') {
                ch = source[index++];
                if (!isLineTerminator(ch.charCodeAt(0))) {
                    switch (ch) {
                    case 'n':
                        cooked += '\n';
                        break;
                    case 'r':
                        cooked += '\r';
                        break;
                    case 't':
                        cooked += '\t';
                        break;
                    case 'u':
                    case 'x':
                        if (source[index] === '{') {
                            ++index;
                            cooked += scanUnicodeCodePointEscape();
                        } else {
                            restore = index;
                            unescaped = scanHexEscape(ch);
                            if (unescaped) {
                                cooked += unescaped;
                            } else {
                                index = restore;
                                cooked += ch;
                            }
                        }
                        break;
                    case 'b':
                        cooked += '\b';
                        break;
                    case 'f':
                        cooked += '\f';
                        break;
                    case 'v':
                        cooked += '\v';
                        break;
 
                    default:
                        if (ch === '0') {
                            if (isDecimalDigit(source.charCodeAt(index))) {
                                // Illegal: \01 \02 and so on
                                throwError(Messages.TemplateOctalLiteral);
                            }
                            cooked += '\0';
                        } else if (isOctalDigit(ch)) {
                            // Illegal: \1 \2
                            throwError(Messages.TemplateOctalLiteral);
                        } else {
                            cooked += ch;
                        }
                        break;
                    }
                } else {
                    ++lineNumber;
                    if (ch === '\r' && source[index] === '\n') {
                        ++index;
                    }
                    lineStart = index;
                }
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                ++lineNumber;
                if (ch === '\r' && source[index] === '\n') {
                    ++index;
                }
                lineStart = index;
                cooked += '\n';
            } else {
                cooked += ch;
            }
        }
 
        if (!terminated) {
            throwUnexpectedToken();
        }
 
        if (!head) {
            state.curlyStack.pop();
        }
 
        return {
            type: Token.Template,
            value: {
                cooked: cooked,
                raw: source.slice(start + 1, index - rawOffset)
            },
            head: head,
            tail: tail,
            lineNumber: lineNumber,
            lineStart: lineStart,
            start: start,
            end: index
        };
    }
 
    function testRegExp(pattern, flags) {
        var tmp = pattern;
 
        if (flags.indexOf('u') >= 0) {
            // Replace each astral symbol and every Unicode escape sequence
            // that possibly represents an astral symbol or a paired surrogate
            // with a single ASCII symbol to avoid throwing on regular
            // expressions that are only valid in combination with the `/u`
            // flag.
            // Note: replacing with the ASCII symbol `x` might cause false
            // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
            // perfectly valid pattern that is equivalent to `[a-b]`, but it
            // would be replaced by `[x-b]` which throws an error.
            tmp = tmp
                .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
                    if (parseInt($1, 16) <= 0x10FFFF) {
                        return 'x';
                    }
                    throwUnexpectedToken(null, Messages.InvalidRegExp);
                })
                .replace(
                    /\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
                    'x'
                );
        }
 
        // First, detect invalid regular expressions.
        try {
            RegExp(tmp);
        } catch (e) {
            throwUnexpectedToken(null, Messages.InvalidRegExp);
        }
 
        // Return a regular expression object for this pattern-flag pair, or
        // `null` in case the current environment doesn't support the flags it
        // uses.
        try {
            return new RegExp(pattern, flags);
        } catch (exception) {
            return null;
        }
    }
 
    function scanRegExpBody() {
        var ch, str, classMarker, terminated, body;
 
        ch = source[index];
        assert(ch === '/', 'Regular expression literal must start with a slash');
        str = source[index++];
 
        classMarker = false;
        terminated = false;
        while (index < length) {
            ch = source[index++];
            str += ch;
            if (ch === '\\') {
                ch = source[index++];
                // ECMA-262 7.8.5
                if (isLineTerminator(ch.charCodeAt(0))) {
                    throwUnexpectedToken(null, Messages.UnterminatedRegExp);
                }
                str += ch;
            } else if (isLineTerminator(ch.charCodeAt(0))) {
                throwUnexpectedToken(null, Messages.UnterminatedRegExp);
            } else if (classMarker) {
                if (ch === ']') {
                    classMarker = false;
                }
            } else {
                if (ch === '/') {
                    terminated = true;
                    break;
                } else if (ch === '[') {
                    classMarker = true;
                }
            }
        }
 
        if (!terminated) {
            throwUnexpectedToken(null, Messages.UnterminatedRegExp);
        }
 
        // Exclude leading and trailing slash.
        body = str.substr(1, str.length - 2);
        return {
            value: body,
            literal: str
        };
    }
 
    function scanRegExpFlags() {
        var ch, str, flags, restore;
 
        str = '';
        flags = '';
        while (index < length) {
            ch = source[index];
            if (!isIdentifierPart(ch.charCodeAt(0))) {
                break;
            }
 
            ++index;
            if (ch === '\\' && index < length) {
                ch = source[index];
                if (ch === 'u') {
                    ++index;
                    restore = index;
                    ch = scanHexEscape('u');
                    if (ch) {
                        flags += ch;
                        for (str += '\\u'; restore < index; ++restore) {
                            str += source[restore];
                        }
                    } else {
                        index = restore;
                        flags += 'u';
                        str += '\\u';
                    }
                    tolerateUnexpectedToken();
                } else {
                    str += '\\';
                    tolerateUnexpectedToken();
                }
            } else {
                flags += ch;
                str += ch;
            }
        }
 
        return {
            value: flags,
            literal: str
        };
    }
 
    function scanRegExp() {
        scanning = true;
        var start, body, flags, value;
 
        lookahead = null;
        skipComment();
        start = index;
 
        body = scanRegExpBody();
        flags = scanRegExpFlags();
        value = testRegExp(body.value, flags.value);
        scanning = false;
        if (extra.tokenize) {
            return {
                type: Token.RegularExpression,
                value: value,
                regex: {
                    pattern: body.value,
                    flags: flags.value
                },
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: start,
                end: index
            };
        }
 
        return {
            literal: body.literal + flags.literal,
            value: value,
            regex: {
                pattern: body.value,
                flags: flags.value
            },
            start: start,
            end: index
        };
    }
 
    function collectRegex() {
        var pos, loc, regex, token;
 
        skipComment();
 
        pos = index;
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart
            }
        };
 
        regex = scanRegExp();
 
        loc.end = {
            line: lineNumber,
            column: index - lineStart
        };
 
        /* istanbul ignore next */
        if (!extra.tokenize) {
            // Pop the previous token, which is likely '/' or '/='
            if (extra.tokens.length > 0) {
                token = extra.tokens[extra.tokens.length - 1];
                if (token.range[0] === pos && token.type === 'Punctuator') {
                    if (token.value === '/' || token.value === '/=') {
                        extra.tokens.pop();
                    }
                }
            }
 
            extra.tokens.push({
                type: 'RegularExpression',
                value: regex.literal,
                regex: regex.regex,
                range: [pos, index],
                loc: loc
            });
        }
 
        return regex;
    }
 
    function isIdentifierName(token) {
        return token.type === Token.Identifier ||
            token.type === Token.Keyword ||
            token.type === Token.BooleanLiteral ||
            token.type === Token.NullLiteral;
    }
 
    function advanceSlash() {
        var prevToken,
            checkToken;
        // Using the following algorithm:
        // https://github.com/mozilla/sweet.js/wiki/design
        prevToken = extra.tokens[extra.tokens.length - 1];
        if (!prevToken) {
            // Nothing before that: it cannot be a division.
            return collectRegex();
        }
        if (prevToken.type === 'Punctuator') {
            if (prevToken.value === ']') {
                return scanPunctuator();
            }
            if (prevToken.value === ')') {
                checkToken = extra.tokens[extra.openParenToken - 1];
                if (checkToken &&
                        checkToken.type === 'Keyword' &&
                        (checkToken.value === 'if' ||
                         checkToken.value === 'while' ||
                         checkToken.value === 'for' ||
                         checkToken.value === 'with')) {
                    return collectRegex();
                }
                return scanPunctuator();
            }
            if (prevToken.value === '}') {
                // Dividing a function by anything makes little sense,
                // but we have to check for that.
                if (extra.tokens[extra.openCurlyToken - 3] &&
                        extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
                    // Anonymous function.
                    checkToken = extra.tokens[extra.openCurlyToken - 4];
                    if (!checkToken) {
                        return scanPunctuator();
                    }
                } else if (extra.tokens[extra.openCurlyToken - 4] &&
                        extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
                    // Named function.
                    checkToken = extra.tokens[extra.openCurlyToken - 5];
                    if (!checkToken) {
                        return collectRegex();
                    }
                } else {
                    return scanPunctuator();
                }
                // checkToken determines whether the function is
                // a declaration or an expression.
                if (FnExprTokens.indexOf(checkToken.value) >= 0) {
                    // It is an expression.
                    return scanPunctuator();
                }
                // It is a declaration.
                return collectRegex();
            }
            return collectRegex();
        }
        if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
            return collectRegex();
        }
        return scanPunctuator();
    }
 
    function advance() {
        var ch, token;
 
        if (index >= length) {
            return {
                type: Token.EOF,
                lineNumber: lineNumber,
                lineStart: lineStart,
                start: index,
                end: index
            };
        }
 
        ch = source.charCodeAt(index);
 
        if (isIdentifierStart(ch)) {
            token = scanIdentifier();
            if (strict && isStrictModeReservedWord(token.value)) {
                token.type = Token.Keyword;
            }
            return token;
        }
 
        // Very common: ( and ) and ;
        if (ch === 0x28 || ch === 0x29 || ch === 0x3B) {
            return scanPunctuator();
        }
 
        // String literal starts with single quote (U+0027) or double quote (U+0022).
        if (ch === 0x27 || ch === 0x22) {
            return scanStringLiteral();
        }
 
        // Dot (.) U+002E can also start a floating-point number, hence the need
        // to check the next character.
        if (ch === 0x2E) {
            if (isDecimalDigit(source.charCodeAt(index + 1))) {
                return scanNumericLiteral();
            }
            return scanPunctuator();
        }
 
        if (isDecimalDigit(ch)) {
            return scanNumericLiteral();
        }
 
        // Slash (/) U+002F can also start a regex.
        if (extra.tokenize && ch === 0x2F) {
            return advanceSlash();
        }
 
        // Template literals start with ` (U+0060) for template head
        // or } (U+007D) for template middle or template tail.
        if (ch === 0x60 || (ch === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) {
            return scanTemplate();
        }
 
        return scanPunctuator();
    }
 
    function collectToken() {
        var loc, token, value, entry;
 
        loc = {
            start: {
                line: lineNumber,
                column: index - lineStart
            }
        };
 
        token = advance();
        loc.end = {
            line: lineNumber,
            column: index - lineStart
        };
 
        if (token.type !== Token.EOF) {
            value = source.slice(token.start, token.end);
            entry = {
                type: TokenName[token.type],
                value: value,
                range: [token.start, token.end],
                loc: loc
            };
            if (token.regex) {
                entry.regex = {
                    pattern: token.regex.pattern,
                    flags: token.regex.flags
                };
            }
            extra.tokens.push(entry);
        }
 
        return token;
    }
 
    function lex() {
        var token;
        scanning = true;
 
        lastIndex = index;
        lastLineNumber = lineNumber;
        lastLineStart = lineStart;
 
        skipComment();
 
        token = lookahead;
 
        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;
 
        lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
        scanning = false;
        return token;
    }
 
    function peek() {
        scanning = true;
 
        skipComment();
 
        lastIndex = index;
        lastLineNumber = lineNumber;
        lastLineStart = lineStart;
 
        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;
 
        lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance();
        scanning = false;
    }
 
    function Position() {
        this.line = startLineNumber;
        this.column = startIndex - startLineStart;
    }
 
    function SourceLocation() {
        this.start = new Position();
        this.end = null;
    }
 
    function WrappingSourceLocation(startToken) {
        this.start = {
            line: startToken.lineNumber,
            column: startToken.start - startToken.lineStart
        };
        this.end = null;
    }
 
    function Node() {
        if (extra.range) {
            this.range = [startIndex, 0];
        }
        if (extra.loc) {
            this.loc = new SourceLocation();
        }
    }
 
    function WrappingNode(startToken) {
        if (extra.range) {
            this.range = [startToken.start, 0];
        }
        if (extra.loc) {
            this.loc = new WrappingSourceLocation(startToken);
        }
    }
 
    WrappingNode.prototype = Node.prototype = {
 
        processComment: function () {
            var lastChild,
                leadingComments,
                trailingComments,
                bottomRight = extra.bottomRightStack,
                i,
                comment,
                last = bottomRight[bottomRight.length - 1];
 
            if (this.type === Syntax.Program) {
                if (this.body.length > 0) {
                    return;
                }
            }
 
            if (extra.trailingComments.length > 0) {
                trailingComments = [];
                for (i = extra.trailingComments.length - 1; i >= 0; --i) {
                    comment = extra.trailingComments[i];
                    if (comment.range[0] >= this.range[1]) {
                        trailingComments.unshift(comment);
                        extra.trailingComments.splice(i, 1);
                    }
                }
                extra.trailingComments = [];
            } else {
                if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) {
                    trailingComments = last.trailingComments;
                    delete last.trailingComments;
                }
            }
 
            // Eating the stack.
            if (last) {
                while (last && last.range[0] >= this.range[0]) {
                    lastChild = last;
                    last = bottomRight.pop();
                }
            }
 
            if (lastChild) {
                if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= this.range[0]) {
                    this.leadingComments = lastChild.leadingComments;
                    lastChild.leadingComments = undefined;
                }
            } else if (extra.leadingComments.length > 0) {
                leadingComments = [];
                for (i = extra.leadingComments.length - 1; i >= 0; --i) {
                    comment = extra.leadingComments[i];
                    if (comment.range[1] <= this.range[0]) {
                        leadingComments.unshift(comment);
                        extra.leadingComments.splice(i, 1);
                    }
                }
            }
 
 
            if (leadingComments && leadingComments.length > 0) {
                this.leadingComments = leadingComments;
            }
            if (trailingComments && trailingComments.length > 0) {
                this.trailingComments = trailingComments;
            }
 
            bottomRight.push(this);
        },
 
        finish: function () {
            if (extra.range) {
                this.range[1] = lastIndex;
            }
            if (extra.loc) {
                this.loc.end = {
                    line: lastLineNumber,
                    column: lastIndex - lastLineStart
                };
                if (extra.source) {
                    this.loc.source = extra.source;
                }
            }
 
            if (extra.attachComment) {
                this.processComment();
            }
        },
 
        finishArrayExpression: function (elements) {
            this.type = Syntax.ArrayExpression;
            this.elements = elements;
            this.finish();
            return this;
        },
 
        finishArrayPattern: function (elements) {
            this.type = Syntax.ArrayPattern;
            this.elements = elements;
            this.finish();
            return this;
        },
 
        finishArrowFunctionExpression: function (params, defaults, body, expression) {
            this.type = Syntax.ArrowFunctionExpression;
            this.id = null;
            this.params = params;
            this.defaults = defaults;
            this.body = body;
            this.generator = false;
            this.expression = expression;
            this.finish();
            return this;
        },
 
        finishAssignmentExpression: function (operator, left, right) {
            this.type = Syntax.AssignmentExpression;
            this.operator = operator;
            this.left = left;
            this.right = right;
            this.finish();
            return this;
        },
 
        finishAssignmentPattern: function (left, right) {
            this.type = Syntax.AssignmentPattern;
            this.left = left;
            this.right = right;
            this.finish();
            return this;
        },
 
        finishBinaryExpression: function (operator, left, right) {
            this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression;
            this.operator = operator;
            this.left = left;
            this.right = right;
            this.finish();
            return this;
        },
 
        finishBlockStatement: function (body) {
            this.type = Syntax.BlockStatement;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishBreakStatement: function (label) {
            this.type = Syntax.BreakStatement;
            this.label = label;
            this.finish();
            return this;
        },
 
        finishCallExpression: function (callee, args) {
            this.type = Syntax.CallExpression;
            this.callee = callee;
            this.arguments = args;
            this.finish();
            return this;
        },
 
        finishCatchClause: function (param, body) {
            this.type = Syntax.CatchClause;
            this.param = param;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishClassBody: function (body) {
            this.type = Syntax.ClassBody;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishClassDeclaration: function (id, superClass, body) {
            this.type = Syntax.ClassDeclaration;
            this.id = id;
            this.superClass = superClass;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishClassExpression: function (id, superClass, body) {
            this.type = Syntax.ClassExpression;
            this.id = id;
            this.superClass = superClass;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishConditionalExpression: function (test, consequent, alternate) {
            this.type = Syntax.ConditionalExpression;
            this.test = test;
            this.consequent = consequent;
            this.alternate = alternate;
            this.finish();
            return this;
        },
 
        finishContinueStatement: function (label) {
            this.type = Syntax.ContinueStatement;
            this.label = label;
            this.finish();
            return this;
        },
 
        finishDebuggerStatement: function () {
            this.type = Syntax.DebuggerStatement;
            this.finish();
            return this;
        },
 
        finishDoWhileStatement: function (body, test) {
            this.type = Syntax.DoWhileStatement;
            this.body = body;
            this.test = test;
            this.finish();
            return this;
        },
 
        finishEmptyStatement: function () {
            this.type = Syntax.EmptyStatement;
            this.finish();
            return this;
        },
 
        finishExpressionStatement: function (expression) {
            this.type = Syntax.ExpressionStatement;
            this.expression = expression;
            this.finish();
            return this;
        },
 
        finishForStatement: function (init, test, update, body) {
            this.type = Syntax.ForStatement;
            this.init = init;
            this.test = test;
            this.update = update;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishForInStatement: function (left, right, body) {
            this.type = Syntax.ForInStatement;
            this.left = left;
            this.right = right;
            this.body = body;
            this.each = false;
            this.finish();
            return this;
        },
 
        finishFunctionDeclaration: function (id, params, defaults, body) {
            this.type = Syntax.FunctionDeclaration;
            this.id = id;
            this.params = params;
            this.defaults = defaults;
            this.body = body;
            this.generator = false;
            this.expression = false;
            this.finish();
            return this;
        },
 
        finishFunctionExpression: function (id, params, defaults, body) {
            this.type = Syntax.FunctionExpression;
            this.id = id;
            this.params = params;
            this.defaults = defaults;
            this.body = body;
            this.generator = false;
            this.expression = false;
            this.finish();
            return this;
        },
 
        finishIdentifier: function (name) {
            this.type = Syntax.Identifier;
            this.name = name;
            this.finish();
            return this;
        },
 
        finishIfStatement: function (test, consequent, alternate) {
            this.type = Syntax.IfStatement;
            this.test = test;
            this.consequent = consequent;
            this.alternate = alternate;
            this.finish();
            return this;
        },
 
        finishLabeledStatement: function (label, body) {
            this.type = Syntax.LabeledStatement;
            this.label = label;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishLiteral: function (token) {
            this.type = Syntax.Literal;
            this.value = token.value;
            this.raw = source.slice(token.start, token.end);
            if (token.regex) {
                this.regex = token.regex;
            }
            this.finish();
            return this;
        },
 
        finishMemberExpression: function (accessor, object, property) {
            this.type = Syntax.MemberExpression;
            this.computed = accessor === '[';
            this.object = object;
            this.property = property;
            this.finish();
            return this;
        },
 
        finishNewExpression: function (callee, args) {
            this.type = Syntax.NewExpression;
            this.callee = callee;
            this.arguments = args;
            this.finish();
            return this;
        },
 
        finishObjectExpression: function (properties) {
            this.type = Syntax.ObjectExpression;
            this.properties = properties;
            this.finish();
            return this;
        },
 
        finishObjectPattern: function (properties) {
            this.type = Syntax.ObjectPattern;
            this.properties = properties;
            this.finish();
            return this;
        },
 
        finishPostfixExpression: function (operator, argument) {
            this.type = Syntax.UpdateExpression;
            this.operator = operator;
            this.argument = argument;
            this.prefix = false;
            this.finish();
            return this;
        },
 
        finishProgram: function (body) {
            this.type = Syntax.Program;
            this.body = body;
            if (sourceType === 'module') {
                // very restrictive for now
                this.sourceType = sourceType;
            }
            this.finish();
            return this;
        },
 
        finishProperty: function (kind, key, computed, value, method, shorthand) {
            this.type = Syntax.Property;
            this.key = key;
            this.computed = computed;
            this.value = value;
            this.kind = kind;
            this.method = method;
            this.shorthand = shorthand;
            this.finish();
            return this;
        },
 
        finishRestElement: function (argument) {
            this.type = Syntax.RestElement;
            this.argument = argument;
            this.finish();
            return this;
        },
 
        finishReturnStatement: function (argument) {
            this.type = Syntax.ReturnStatement;
            this.argument = argument;
            this.finish();
            return this;
        },
 
        finishSequenceExpression: function (expressions) {
            this.type = Syntax.SequenceExpression;
            this.expressions = expressions;
            this.finish();
            return this;
        },
 
        finishSpreadElement: function (argument) {
            this.type = Syntax.SpreadElement;
            this.argument = argument;
            this.finish();
            return this;
        },
 
        finishSwitchCase: function (test, consequent) {
            this.type = Syntax.SwitchCase;
            this.test = test;
            this.consequent = consequent;
            this.finish();
            return this;
        },
 
        finishSuper: function () {
            this.type = Syntax.Super;
            this.finish();
            return this;
        },
 
        finishSwitchStatement: function (discriminant, cases) {
            this.type = Syntax.SwitchStatement;
            this.discriminant = discriminant;
            this.cases = cases;
            this.finish();
            return this;
        },
 
        finishTaggedTemplateExpression: function (tag, quasi) {
            this.type = Syntax.TaggedTemplateExpression;
            this.tag = tag;
            this.quasi = quasi;
            this.finish();
            return this;
        },
 
        finishTemplateElement: function (value, tail) {
            this.type = Syntax.TemplateElement;
            this.value = value;
            this.tail = tail;
            this.finish();
            return this;
        },
 
        finishTemplateLiteral: function (quasis, expressions) {
            this.type = Syntax.TemplateLiteral;
            this.quasis = quasis;
            this.expressions = expressions;
            this.finish();
            return this;
        },
 
        finishThisExpression: function () {
            this.type = Syntax.ThisExpression;
            this.finish();
            return this;
        },
 
        finishThrowStatement: function (argument) {
            this.type = Syntax.ThrowStatement;
            this.argument = argument;
            this.finish();
            return this;
        },
 
        finishTryStatement: function (block, handler, finalizer) {
            this.type = Syntax.TryStatement;
            this.block = block;
            this.guardedHandlers = [];
            this.handlers = handler ? [ handler ] : [];
            this.handler = handler;
            this.finalizer = finalizer;
            this.finish();
            return this;
        },
 
        finishUnaryExpression: function (operator, argument) {
            this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression;
            this.operator = operator;
            this.argument = argument;
            this.prefix = true;
            this.finish();
            return this;
        },
 
        finishVariableDeclaration: function (declarations) {
            this.type = Syntax.VariableDeclaration;
            this.declarations = declarations;
            this.kind = 'var';
            this.finish();
            return this;
        },
 
        finishLexicalDeclaration: function (declarations, kind) {
            this.type = Syntax.VariableDeclaration;
            this.declarations = declarations;
            this.kind = kind;
            this.finish();
            return this;
        },
 
        finishVariableDeclarator: function (id, init) {
            this.type = Syntax.VariableDeclarator;
            this.id = id;
            this.init = init;
            this.finish();
            return this;
        },
 
        finishWhileStatement: function (test, body) {
            this.type = Syntax.WhileStatement;
            this.test = test;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishWithStatement: function (object, body) {
            this.type = Syntax.WithStatement;
            this.object = object;
            this.body = body;
            this.finish();
            return this;
        },
 
        finishExportSpecifier: function (local, exported) {
            this.type = Syntax.ExportSpecifier;
            this.exported = exported || local;
            this.local = local;
            this.finish();
            return this;
        },
 
        finishImportDefaultSpecifier: function (local) {
            this.type = Syntax.ImportDefaultSpecifier;
            this.local = local;
            this.finish();
            return this;
        },
 
        finishImportNamespaceSpecifier: function (local) {
            this.type = Syntax.ImportNamespaceSpecifier;
            this.local = local;
            this.finish();
            return this;
        },
 
        finishExportNamedDeclaration: function (declaration, specifiers, src) {
            this.type = Syntax.ExportNamedDeclaration;
            this.declaration = declaration;
            this.specifiers = specifiers;
            this.source = src;
            this.finish();
            return this;
        },
 
        finishExportDefaultDeclaration: function (declaration) {
            this.type = Syntax.ExportDefaultDeclaration;
            this.declaration = declaration;
            this.finish();
            return this;
        },
 
        finishExportAllDeclaration: function (src) {
            this.type = Syntax.ExportAllDeclaration;
            this.source = src;
            this.finish();
            return this;
        },
 
        finishImportSpecifier: function (local, imported) {
            this.type = Syntax.ImportSpecifier;
            this.local = local || imported;
            this.imported = imported;
            this.finish();
            return this;
        },
 
        finishImportDeclaration: function (specifiers, src) {
            this.type = Syntax.ImportDeclaration;
            this.specifiers = specifiers;
            this.source = src;
            this.finish();
            return this;
        }
    };
 
 
    function recordError(error) {
        var e, existing;
 
        for (e = 0; e < extra.errors.length; e++) {
            existing = extra.errors[e];
            // Prevent duplicated error.
            /* istanbul ignore next */
            if (existing.index === error.index && existing.message === error.message) {
                return;
            }
        }
 
        extra.errors.push(error);
    }
 
    function createError(line, pos, description) {
        var error = new Error('Line ' + line + ': ' + description);
        error.index = pos;
        error.lineNumber = line;
        error.column = pos - (scanning ? lineStart : lastLineStart) + 1;
        error.description = description;
        return error;
    }
 
    // Throw an exception
 
    function throwError(messageFormat) {
        var args, msg;
 
        args = Array.prototype.slice.call(arguments, 1);
        msg = messageFormat.replace(/%(\d)/g,
            function (whole, idx) {
                assert(idx < args.length, 'Message reference must be in range');
                return args[idx];
            }
        );
 
        throw createError(lastLineNumber, lastIndex, msg);
    }
 
    function tolerateError(messageFormat) {
        var args, msg, error;
 
        args = Array.prototype.slice.call(arguments, 1);
        /* istanbul ignore next */
        msg = messageFormat.replace(/%(\d)/g,
            function (whole, idx) {
                assert(idx < args.length, 'Message reference must be in range');
                return args[idx];
            }
        );
 
        error = createError(lineNumber, lastIndex, msg);
        if (extra.errors) {
            recordError(error);
        } else {
            throw error;
        }
    }
 
    // Throw an exception because of the token.
 
    function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;
 
        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;
 
                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }
 
            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }
 
        msg = msg.replace('%0', value);
 
        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }
 
    function throwUnexpectedToken(token, message) {
        throw unexpectedTokenError(token, message);
    }
 
    function tolerateUnexpectedToken(token, message) {
        var error = unexpectedTokenError(token, message);
        if (extra.errors) {
            recordError(error);
        } else {
            throw error;
        }
    }
 
    // Expect the next token to match the specified punctuator.
    // If not, an exception will be thrown.
 
    function expect(value) {
        var token = lex();
        if (token.type !== Token.Punctuator || token.value !== value) {
            throwUnexpectedToken(token);
        }
    }
 
    /**
     * @name expectCommaSeparator
     * @description Quietly expect a comma when in tolerant mode, otherwise delegates
     * to <code>expect(value)</code>
     * @since 2.0
     */
    function expectCommaSeparator() {
        var token;
 
        if (extra.errors) {
            token = lookahead;
            if (token.type === Token.Punctuator && token.value === ',') {
                lex();
            } else if (token.type === Token.Punctuator && token.value === ';') {
                lex();
                tolerateUnexpectedToken(token);
            } else {
                tolerateUnexpectedToken(token, Messages.UnexpectedToken);
            }
        } else {
            expect(',');
        }
    }
 
    // Expect the next token to match the specified keyword.
    // If not, an exception will be thrown.
 
    function expectKeyword(keyword) {
        var token = lex();
        if (token.type !== Token.Keyword || token.value !== keyword) {
            throwUnexpectedToken(token);
        }
    }
 
    // Return true if the next token matches the specified punctuator.
 
    function match(value) {
        return lookahead.type === Token.Punctuator && lookahead.value === value;
    }
 
    // Return true if the next token matches the specified keyword
 
    function matchKeyword(keyword) {
        return lookahead.type === Token.Keyword && lookahead.value === keyword;
    }
 
    // Return true if the next token matches the specified contextual keyword
    // (where an identifier is sometimes a keyword depending on the context)
 
    function matchContextualKeyword(keyword) {
        return lookahead.type === Token.Identifier && lookahead.value === keyword;
    }
 
    // Return true if the next token is an assignment operator
 
    function matchAssign() {
        var op;
 
        if (lookahead.type !== Token.Punctuator) {
            return false;
        }
        op = lookahead.value;
        return op === '=' ||
            op === '*=' ||
            op === '/=' ||
            op === '%=' ||
            op === '+=' ||
            op === '-=' ||
            op === '<<=' ||
            op === '>>=' ||
            op === '>>>=' ||
            op === '&=' ||
            op === '^=' ||
            op === '|=';
    }
 
    function consumeSemicolon() {
        // Catch the very common case first: immediately a semicolon (U+003B).
        if (source.charCodeAt(startIndex) === 0x3B || match(';')) {
            lex();
            return;
        }
 
        if (hasLineTerminator) {
            return;
        }
 
        // FIXME(ikarienator): this is seemingly an issue in the previous location info convention.
        lastIndex = startIndex;
        lastLineNumber = startLineNumber;
        lastLineStart = startLineStart;
 
        if (lookahead.type !== Token.EOF && !match('}')) {
            throwUnexpectedToken(lookahead);
        }
    }
 
    // Cover grammar support.
    //
    // When an assignment expression position starts with an left parenthesis, the determination of the type
    // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
    // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
    //
    // There are three productions that can be parsed in a parentheses pair that needs to be determined
    // after the outermost pair is closed. They are:
    //
    //   1. AssignmentExpression
    //   2. BindingElements
    //   3. AssignmentTargets
    //
    // In order to avoid exponential backtracking, we use two flags to denote if the production can be
    // binding element or assignment target.
    //
    // The three productions have the relationship:
    //
    //   BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
    //
    // with a single exception that CoverInitializedName when used directly in an Expression, generates
    // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
    // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
    //
    // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
    // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
    // the CoverInitializedName check is conducted.
    //
    // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
    // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
    // pattern. The CoverInitializedName check is deferred.
    function isolateCoverGrammar(parser) {
        var oldIsBindingElement = isBindingElement,
            oldIsAssignmentTarget = isAssignmentTarget,
            oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
            result;
        isBindingElement = true;
        isAssignmentTarget = true;
        firstCoverInitializedNameError = null;
        result = parser();
        if (firstCoverInitializedNameError !== null) {
            throwUnexpectedToken(firstCoverInitializedNameError);
        }
        isBindingElement = oldIsBindingElement;
        isAssignmentTarget = oldIsAssignmentTarget;
        firstCoverInitializedNameError = oldFirstCoverInitializedNameError;
        return result;
    }
 
    function inheritCoverGrammar(parser) {
        var oldIsBindingElement = isBindingElement,
            oldIsAssignmentTarget = isAssignmentTarget,
            oldFirstCoverInitializedNameError = firstCoverInitializedNameError,
            result;
        isBindingElement = true;
        isAssignmentTarget = true;
        firstCoverInitializedNameError = null;
        result = parser();
        isBindingElement = isBindingElement && oldIsBindingElement;
        isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget;
        firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError;
        return result;
    }
 
    function parseArrayPattern() {
        var node = new Node(), elements = [], rest, restNode;
        expect('[');
 
        while (!match(']')) {
            if (match(',')) {
                lex();
                elements.push(null);
            } else {
                if (match('...')) {
                    restNode = new Node();
                    lex();
                    rest = parseVariableIdentifier();
                    elements.push(restNode.finishRestElement(rest));
                    break;
                } else {
                    elements.push(parsePatternWithDefault());
                }
                if (!match(']')) {
                    expect(',');
                }
            }
 
        }
 
        expect(']');
 
        return node.finishArrayPattern(elements);
    }
 
    function parsePropertyPattern() {
        var node = new Node(), key, computed = match('['), init;
        if (lookahead.type === Token.Identifier) {
            key = parseVariableIdentifier();
            if (match('=')) {
                lex();
                init = parseAssignmentExpression();
                return node.finishProperty(
                    'init', key, false,
                    new WrappingNode(key).finishAssignmentPattern(key, init), false, false);
            } else if (!match(':')) {
                return node.finishProperty('init', key, false, key, false, true);
            }
        } else {
            key = parseObjectPropertyKey();
        }
        expect(':');
        init = parsePatternWithDefault();
        return node.finishProperty('init', key, computed, init, false, false);
    }
 
    function parseObjectPattern() {
        var node = new Node(), properties = [];
 
        expect('{');
 
        while (!match('}')) {
            properties.push(parsePropertyPattern());
            if (!match('}')) {
                expect(',');
            }
        }
 
        lex();
 
        return node.finishObjectPattern(properties);
    }
 
    function parsePattern() {
        if (lookahead.type === Token.Identifier) {
            return parseVariableIdentifier();
        } else if (match('[')) {
            return parseArrayPattern();
        } else if (match('{')) {
            return parseObjectPattern();
        }
        throwUnexpectedToken(lookahead);
    }
 
    function parsePatternWithDefault() {
        var startToken = lookahead, pattern, right;
        pattern = parsePattern();
        if (match('=')) {
            lex();
            right = isolateCoverGrammar(parseAssignmentExpression);
            pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right);
        }
        return pattern;
    }
 
    // 11.1.4 Array Initialiser
 
    function parseArrayInitialiser() {
        var elements = [], node = new Node(), restSpread;
 
        expect('[');
 
        while (!match(']')) {
            if (match(',')) {
                lex();
                elements.push(null);
            } else if (match('...')) {
                restSpread = new Node();
                lex();
                restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression));
 
                if (!match(']')) {
                    isAssignmentTarget = isBindingElement = false;
                    expect(',');
                }
                elements.push(restSpread);
            } else {
                elements.push(inheritCoverGrammar(parseAssignmentExpression));
 
                if (!match(']')) {
                    expect(',');
                }
            }
        }
 
        lex();
 
        return node.finishArrayExpression(elements);
    }
 
    // 11.1.5 Object Initialiser
 
    function parsePropertyFunction(node, paramInfo) {
        var previousStrict, body;
 
        isAssignmentTarget = isBindingElement = false;
 
        previousStrict = strict;
        body = isolateCoverGrammar(parseFunctionSourceElements);
 
        if (strict && paramInfo.firstRestricted) {
            tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message);
        }
        if (strict && paramInfo.stricted) {
            tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message);
        }
 
        strict = previousStrict;
        return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body);
    }
 
    function parsePropertyMethodFunction() {
        var params, method, node = new Node();
 
        params = parseParams();
        method = parsePropertyFunction(node, params);
 
        return method;
    }
 
    function parseObjectPropertyKey() {
        var token, node = new Node(), expr;
 
        token = lex();
 
        // Note: This function is called only from parseObjectProperty(), where
        // EOF and Punctuator tokens are already filtered out.
 
        switch (token.type) {
        case Token.StringLiteral:
        case Token.NumericLiteral:
            if (strict && token.octal) {
                tolerateUnexpectedToken(token, Messages.StrictOctalLiteral);
            }
            return node.finishLiteral(token);
        case Token.Identifier:
        case Token.BooleanLiteral:
        case Token.NullLiteral:
        case Token.Keyword:
            return node.finishIdentifier(token.value);
        case Token.Punctuator:
            if (token.value === '[') {
                expr = isolateCoverGrammar(parseAssignmentExpression);
                expect(']');
                return expr;
            }
            break;
        }
        throwUnexpectedToken(token);
    }
 
    function lookaheadPropertyName() {
        switch (lookahead.type) {
        case Token.Identifier:
        case Token.StringLiteral:
        case Token.BooleanLiteral:
        case Token.NullLiteral:
        case Token.NumericLiteral:
        case Token.Keyword:
            return true;
        case Token.Punctuator:
            return lookahead.value === '[';
        }
        return false;
    }
 
    // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals,
    // it might be called at a position where there is in fact a short hand identifier pattern or a data property.
    // This can only be determined after we consumed up to the left parentheses.
    //
    // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller
    // is responsible to visit other options.
    function tryParseMethodDefinition(token, key, computed, node) {
        var value, options, methodNode;
 
        if (token.type === Token.Identifier) {
            // check for `get` and `set`;
 
            if (token.value === 'get' && lookaheadPropertyName()) {
                computed = match('[');
                key = parseObjectPropertyKey();
                methodNode = new Node();
                expect('(');
                expect(')');
                value = parsePropertyFunction(methodNode, {
                    params: [],
                    defaults: [],
                    stricted: null,
                    firstRestricted: null,
                    message: null
                });
                return node.finishProperty('get', key, computed, value, false, false);
            } else if (token.value === 'set' && lookaheadPropertyName()) {
                computed = match('[');
                key = parseObjectPropertyKey();
                methodNode = new Node();
                expect('(');
 
                options = {
                    params: [],
                    defaultCount: 0,
                    defaults: [],
                    firstRestricted: null,
                    paramSet: {}
                };
                if (match(')')) {
                    tolerateUnexpectedToken(lookahead);
                } else {
                    parseParam(options);
                    if (options.defaultCount === 0) {
                        options.defaults = [];
                    }
                }
                expect(')');
 
                value = parsePropertyFunction(methodNode, options);
                return node.finishProperty('set', key, computed, value, false, false);
            }
        }
 
        if (match('(')) {
            value = parsePropertyMethodFunction();
            return node.finishProperty('init', key, computed, value, true, false);
        }
 
        // Not a MethodDefinition.
        return null;
    }
 
    function checkProto(key, computed, hasProto) {
        if (computed === false && (key.type === Syntax.Identifier && key.name === '__proto__' ||
            key.type === Syntax.Literal && key.value === '__proto__')) {
            if (hasProto.value) {
                tolerateError(Messages.DuplicateProtoProperty);
            } else {
                hasProto.value = true;
            }
        }
    }
 
    function parseObjectProperty(hasProto) {
        var token = lookahead, node = new Node(), computed, key, maybeMethod, value;
 
        computed = match('[');
        key = parseObjectPropertyKey();
        maybeMethod = tryParseMethodDefinition(token, key, computed, node);
 
        if (maybeMethod) {
            checkProto(maybeMethod.key, maybeMethod.computed, hasProto);
            // finished
            return maybeMethod;
        }
 
        // init property or short hand property.
        checkProto(key, computed, hasProto);
 
        if (match(':')) {
            lex();
            value = inheritCoverGrammar(parseAssignmentExpression);
            return node.finishProperty('init', key, computed, value, false, false);
        }
 
        if (token.type === Token.Identifier) {
            if (match('=')) {
                firstCoverInitializedNameError = lookahead;
                lex();
                value = isolateCoverGrammar(parseAssignmentExpression);
                return node.finishProperty('init', key, computed,
                    new WrappingNode(token).finishAssignmentPattern(key, value), false, true);
            }
            return node.finishProperty('init', key, computed, key, false, true);
        }
 
        throwUnexpectedToken(lookahead);
    }
 
    function parseObjectInitialiser() {
        var properties = [], hasProto = {value: false}, node = new Node();
 
        expect('{');
 
        while (!match('}')) {
            properties.push(parseObjectProperty(hasProto));
 
            if (!match('}')) {
                expectCommaSeparator();
            }
        }
 
        expect('}');
 
        return node.finishObjectExpression(properties);
    }
 
    function reinterpretExpressionAsPattern(expr) {
        var i;
        switch (expr.type) {
        case Syntax.Identifier:
        case Syntax.MemberExpression:
        case Syntax.RestElement:
        case Syntax.AssignmentPattern:
            break;
        case Syntax.SpreadElement:
            expr.type = Syntax.RestElement;
            reinterpretExpressionAsPattern(expr.argument);
            break;
        case Syntax.ArrayExpression:
            expr.type = Syntax.ArrayPattern;
            for (i = 0; i < expr.elements.length; i++) {
                if (expr.elements[i] !== null) {
                    reinterpretExpressionAsPattern(expr.elements[i]);
                }
            }
            break;
        case Syntax.ObjectExpression:
            expr.type = Syntax.ObjectPattern;
            for (i = 0; i < expr.properties.length; i++) {
                reinterpretExpressionAsPattern(expr.properties[i].value);
            }
            break;
        case Syntax.AssignmentExpression:
            expr.type = Syntax.AssignmentPattern;
            reinterpretExpressionAsPattern(expr.left);
            break;
        default:
            // Allow other node type for tolerant parsing.
            break;
        }
    }
 
    function parseTemplateElement(option) {
        var node, token;
 
        if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) {
            throwUnexpectedToken();
        }
 
        node = new Node();
        token = lex();
 
        return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail);
    }
 
    function parseTemplateLiteral() {
        var quasi, quasis, expressions, node = new Node();
 
        quasi = parseTemplateElement({ head: true });
        quasis = [ quasi ];
        expressions = [];
 
        while (!quasi.tail) {
            expressions.push(parseExpression());
            quasi = parseTemplateElement({ head: false });
            quasis.push(quasi);
        }
 
        return node.finishTemplateLiteral(quasis, expressions);
    }
 
    // 11.1.6 The Grouping Operator
 
    function parseGroupExpression() {
        var expr, expressions, startToken, i;
 
        expect('(');
 
        if (match(')')) {
            lex();
            if (!match('=>')) {
                expect('=>');
            }
            return {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: []
            };
        }
 
        startToken = lookahead;
        if (match('...')) {
            expr = parseRestElement();
            expect(')');
            if (!match('=>')) {
                expect('=>');
            }
            return {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: [expr]
            };
        }
 
        isBindingElement = true;
        expr = inheritCoverGrammar(parseAssignmentExpression);
 
        if (match(',')) {
            isAssignmentTarget = false;
            expressions = [expr];
 
            while (startIndex < length) {
                if (!match(',')) {
                    break;
                }
                lex();
 
                if (match('...')) {
                    if (!isBindingElement) {
                        throwUnexpectedToken(lookahead);
                    }
                    expressions.push(parseRestElement());
                    expect(')');
                    if (!match('=>')) {
                        expect('=>');
                    }
                    isBindingElement = false;
                    for (i = 0; i < expressions.length; i++) {
                        reinterpretExpressionAsPattern(expressions[i]);
                    }
                    return {
                        type: PlaceHolders.ArrowParameterPlaceHolder,
                        params: expressions
                    };
                }
 
                expressions.push(inheritCoverGrammar(parseAssignmentExpression));
            }
 
            expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
        }
 
 
        expect(')');
 
        if (match('=>')) {
            if (!isBindingElement) {
                throwUnexpectedToken(lookahead);
            }
 
            if (expr.type === Syntax.SequenceExpression) {
                for (i = 0; i < expr.expressions.length; i++) {
                    reinterpretExpressionAsPattern(expr.expressions[i]);
                }
            } else {
                reinterpretExpressionAsPattern(expr);
            }
 
            expr = {
                type: PlaceHolders.ArrowParameterPlaceHolder,
                params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr]
            };
        }
        isBindingElement = false;
        return expr;
    }
 
 
    // 11.1 Primary Expressions
 
    function parsePrimaryExpression() {
        var type, token, expr, node;
 
        if (match('(')) {
            isBindingElement = false;
            return inheritCoverGrammar(parseGroupExpression);
        }
 
        if (match('[')) {
            return inheritCoverGrammar(parseArrayInitialiser);
        }
 
        if (match('{')) {
            return inheritCoverGrammar(parseObjectInitialiser);
        }
 
        type = lookahead.type;
        node = new Node();
 
        if (type === Token.Identifier) {
            expr = node.finishIdentifier(lex().value);
        } else if (type === Token.StringLiteral || type === Token.NumericLiteral) {
            isAssignmentTarget = isBindingElement = false;
            if (strict && lookahead.octal) {
                tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral);
            }
            expr = node.finishLiteral(lex());
        } else if (type === Token.Keyword) {
            isAssignmentTarget = isBindingElement = false;
            if (matchKeyword('function')) {
                return parseFunctionExpression();
            }
            if (matchKeyword('this')) {
                lex();
                return node.finishThisExpression();
            }
            if (matchKeyword('class')) {
                return parseClassExpression();
            }
            throwUnexpectedToken(lex());
        } else if (type === Token.BooleanLiteral) {
            isAssignmentTarget = isBindingElement = false;
            token = lex();
            token.value = (token.value === 'true');
            expr = node.finishLiteral(token);
        } else if (type === Token.NullLiteral) {
            isAssignmentTarget = isBindingElement = false;
            token = lex();
            token.value = null;
            expr = node.finishLiteral(token);
        } else if (match('/') || match('/=')) {
            isAssignmentTarget = isBindingElement = false;
            index = startIndex;
 
            if (typeof extra.tokens !== 'undefined') {
                token = collectRegex();
            } else {
                token = scanRegExp();
            }
            lex();
            expr = node.finishLiteral(token);
        } else if (type === Token.Template) {
            expr = parseTemplateLiteral();
        } else {
            throwUnexpectedToken(lex());
        }
 
        return expr;
    }
 
    // 11.2 Left-Hand-Side Expressions
 
    function parseArguments() {
        var args = [];
 
        expect('(');
 
        if (!match(')')) {
            while (startIndex < length) {
                args.push(isolateCoverGrammar(parseAssignmentExpression));
                if (match(')')) {
                    break;
                }
                expectCommaSeparator();
            }
        }
 
        expect(')');
 
        return args;
    }
 
    function parseNonComputedProperty() {
        var token, node = new Node();
 
        token = lex();
 
        if (!isIdentifierName(token)) {
            throwUnexpectedToken(token);
        }
 
        return node.finishIdentifier(token.value);
    }
 
    function parseNonComputedMember() {
        expect('.');
 
        return parseNonComputedProperty();
    }
 
    function parseComputedMember() {
        var expr;
 
        expect('[');
 
        expr = isolateCoverGrammar(parseExpression);
 
        expect(']');
 
        return expr;
    }
 
    function parseNewExpression() {
        var callee, args, node = new Node();
 
        expectKeyword('new');
        callee = isolateCoverGrammar(parseLeftHandSideExpression);
        args = match('(') ? parseArguments() : [];
 
        isAssignmentTarget = isBindingElement = false;
 
        return node.finishNewExpression(callee, args);
    }
 
    function parseLeftHandSideExpressionAllowCall() {
        var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn;
 
        startToken = lookahead;
        state.allowIn = true;
 
        if (matchKeyword('super') && state.inFunctionBody) {
            expr = new Node();
            lex();
            expr = expr.finishSuper();
            if (!match('(') && !match('.') && !match('[')) {
                throwUnexpectedToken(lookahead);
            }
        } else {
            expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
        }
 
        for (;;) {
            if (match('.')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseNonComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
            } else if (match('(')) {
                isBindingElement = false;
                isAssignmentTarget = false;
                args = parseArguments();
                expr = new WrappingNode(startToken).finishCallExpression(expr, args);
            } else if (match('[')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
            } else if (lookahead.type === Token.Template && lookahead.head) {
                quasi = parseTemplateLiteral();
                expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
            } else {
                break;
            }
        }
        state.allowIn = previousAllowIn;
 
        return expr;
    }
 
    function parseLeftHandSideExpression() {
        var quasi, expr, property, startToken;
        assert(state.allowIn, 'callee of new expression always allow in keyword.');
 
        startToken = lookahead;
 
        if (matchKeyword('super') && state.inFunctionBody) {
            expr = new Node();
            lex();
            expr = expr.finishSuper();
            if (!match('[') && !match('.')) {
                throwUnexpectedToken(lookahead);
            }
        } else {
            expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression);
        }
 
        for (;;) {
            if (match('[')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property);
            } else if (match('.')) {
                isBindingElement = false;
                isAssignmentTarget = true;
                property = parseNonComputedMember();
                expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property);
            } else if (lookahead.type === Token.Template && lookahead.head) {
                quasi = parseTemplateLiteral();
                expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi);
            } else {
                break;
            }
        }
        return expr;
    }
 
    // 11.3 Postfix Expressions
 
    function parsePostfixExpression() {
        var expr, token, startToken = lookahead;
 
        expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall);
 
        if (!hasLineTerminator && lookahead.type === Token.Punctuator) {
            if (match('++') || match('--')) {
                // 11.3.1, 11.3.2
                if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                    tolerateError(Messages.StrictLHSPostfix);
                }
 
                if (!isAssignmentTarget) {
                    tolerateError(Messages.InvalidLHSInAssignment);
                }
 
                isAssignmentTarget = isBindingElement = false;
 
                token = lex();
                expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr);
            }
        }
 
        return expr;
    }
 
    // 11.4 Unary Operators
 
    function parseUnaryExpression() {
        var token, expr, startToken;
 
        if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
            expr = parsePostfixExpression();
        } else if (match('++') || match('--')) {
            startToken = lookahead;
            token = lex();
            expr = inheritCoverGrammar(parseUnaryExpression);
            // 11.4.4, 11.4.5
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                tolerateError(Messages.StrictLHSPrefix);
            }
 
            if (!isAssignmentTarget) {
                tolerateError(Messages.InvalidLHSInAssignment);
            }
            expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
            isAssignmentTarget = isBindingElement = false;
        } else if (match('+') || match('-') || match('~') || match('!')) {
            startToken = lookahead;
            token = lex();
            expr = inheritCoverGrammar(parseUnaryExpression);
            expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
            isAssignmentTarget = isBindingElement = false;
        } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
            startToken = lookahead;
            token = lex();
            expr = inheritCoverGrammar(parseUnaryExpression);
            expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr);
            if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
                tolerateError(Messages.StrictDelete);
            }
            isAssignmentTarget = isBindingElement = false;
        } else {
            expr = parsePostfixExpression();
        }
 
        return expr;
    }
 
    function binaryPrecedence(token, allowIn) {
        var prec = 0;
 
        if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
            return 0;
        }
 
        switch (token.value) {
        case '||':
            prec = 1;
            break;
 
        case '&&':
            prec = 2;
            break;
 
        case '|':
            prec = 3;
            break;
 
        case '^':
            prec = 4;
            break;
 
        case '&':
            prec = 5;
            break;
 
        case '==':
        case '!=':
        case '===':
        case '!==':
            prec = 6;
            break;
 
        case '<':
        case '>':
        case '<=':
        case '>=':
        case 'instanceof':
            prec = 7;
            break;
 
        case 'in':
            prec = allowIn ? 7 : 0;
            break;
 
        case '<<':
        case '>>':
        case '>>>':
            prec = 8;
            break;
 
        case '+':
        case '-':
            prec = 9;
            break;
 
        case '*':
        case '/':
        case '%':
            prec = 11;
            break;
 
        default:
            break;
        }
 
        return prec;
    }
 
    // 11.5 Multiplicative Operators
    // 11.6 Additive Operators
    // 11.7 Bitwise Shift Operators
    // 11.8 Relational Operators
    // 11.9 Equality Operators
    // 11.10 Binary Bitwise Operators
    // 11.11 Binary Logical Operators
 
    function parseBinaryExpression() {
        var marker, markers, expr, token, prec, stack, right, operator, left, i;
 
        marker = lookahead;
        left = inheritCoverGrammar(parseUnaryExpression);
 
        token = lookahead;
        prec = binaryPrecedence(token, state.allowIn);
        if (prec === 0) {
            return left;
        }
        isAssignmentTarget = isBindingElement = false;
        token.prec = prec;
        lex();
 
        markers = [marker, lookahead];
        right = isolateCoverGrammar(parseUnaryExpression);
 
        stack = [left, token, right];
 
        while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) {
 
            // Reduce: make a binary expression from the three topmost entries.
            while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
                right = stack.pop();
                operator = stack.pop().value;
                left = stack.pop();
                markers.pop();
                expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right);
                stack.push(expr);
            }
 
            // Shift.
            token = lex();
            token.prec = prec;
            stack.push(token);
            markers.push(lookahead);
            expr = isolateCoverGrammar(parseUnaryExpression);
            stack.push(expr);
        }
 
        // Final reduce to clean-up the stack.
        i = stack.length - 1;
        expr = stack[i];
        markers.pop();
        while (i > 1) {
            expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
            i -= 2;
        }
 
        return expr;
    }
 
 
    // 11.12 Conditional Operator
 
    function parseConditionalExpression() {
        var expr, previousAllowIn, consequent, alternate, startToken;
 
        startToken = lookahead;
 
        expr = inheritCoverGrammar(parseBinaryExpression);
        if (match('?')) {
            lex();
            previousAllowIn = state.allowIn;
            state.allowIn = true;
            consequent = isolateCoverGrammar(parseAssignmentExpression);
            state.allowIn = previousAllowIn;
            expect(':');
            alternate = isolateCoverGrammar(parseAssignmentExpression);
 
            expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate);
            isAssignmentTarget = isBindingElement = false;
        }
 
        return expr;
    }
 
    // [ES6] 14.2 Arrow Function
 
    function parseConciseBody() {
        if (match('{')) {
            return parseFunctionSourceElements();
        }
        return isolateCoverGrammar(parseAssignmentExpression);
    }
 
    function checkPatternParam(options, param) {
        var i;
        switch (param.type) {
        case Syntax.Identifier:
            validateParam(options, param, param.name);
            break;
        case Syntax.RestElement:
            checkPatternParam(options, param.argument);
            break;
        case Syntax.AssignmentPattern:
            checkPatternParam(options, param.left);
            break;
        case Syntax.ArrayPattern:
            for (i = 0; i < param.elements.length; i++) {
                if (param.elements[i] !== null) {
                    checkPatternParam(options, param.elements[i]);
                }
            }
            break;
        default:
            assert(param.type === Syntax.ObjectPattern, 'Invalid type');
            for (i = 0; i < param.properties.length; i++) {
                checkPatternParam(options, param.properties[i].value);
            }
            break;
        }
    }
    function reinterpretAsCoverFormalsList(expr) {
        var i, len, param, params, defaults, defaultCount, options, token;
 
        defaults = [];
        defaultCount = 0;
        params = [expr];
 
        switch (expr.type) {
        case Syntax.Identifier:
            break;
        case PlaceHolders.ArrowParameterPlaceHolder:
            params = expr.params;
            break;
        default:
            return null;
        }
 
        options = {
            paramSet: {}
        };
 
        for (i = 0, len = params.length; i < len; i += 1) {
            param = params[i];
            switch (param.type) {
            case Syntax.AssignmentPattern:
                params[i] = param.left;
                defaults.push(param.right);
                ++defaultCount;
                checkPatternParam(options, param.left);
                break;
            default:
                checkPatternParam(options, param);
                params[i] = param;
                defaults.push(null);
                break;
            }
        }
 
        if (options.message === Messages.StrictParamDupe) {
            token = strict ? options.stricted : options.firstRestricted;
            throwUnexpectedToken(token, options.message);
        }
 
        if (defaultCount === 0) {
            defaults = [];
        }
 
        return {
            params: params,
            defaults: defaults,
            stricted: options.stricted,
            firstRestricted: options.firstRestricted,
            message: options.message
        };
    }
 
    function parseArrowFunctionExpression(options, node) {
        var previousStrict, body;
 
        if (hasLineTerminator) {
            tolerateUnexpectedToken(lookahead);
        }
        expect('=>');
        previousStrict = strict;
 
        body = parseConciseBody();
 
        if (strict && options.firstRestricted) {
            throwUnexpectedToken(options.firstRestricted, options.message);
        }
        if (strict && options.stricted) {
            tolerateUnexpectedToken(options.stricted, options.message);
        }
 
        strict = previousStrict;
 
        return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement);
    }
 
    // 11.13 Assignment Operators
 
    function parseAssignmentExpression() {
        var token, expr, right, list, startToken;
 
        startToken = lookahead;
        token = lookahead;
 
        expr = parseConditionalExpression();
 
        if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
            isAssignmentTarget = isBindingElement = false;
            list = reinterpretAsCoverFormalsList(expr);
 
            if (list) {
                firstCoverInitializedNameError = null;
                return parseArrowFunctionExpression(list, new WrappingNode(startToken));
            }
 
            return expr;
        }
 
        if (matchAssign()) {
            if (!isAssignmentTarget) {
                tolerateError(Messages.InvalidLHSInAssignment);
            }
 
            // 11.13.1
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
            }
 
            if (!match('=')) {
                isAssignmentTarget = isBindingElement = false;
            } else {
                reinterpretExpressionAsPattern(expr);
            }
 
            token = lex();
            right = isolateCoverGrammar(parseAssignmentExpression);
            expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
            firstCoverInitializedNameError = null;
        }
 
        return expr;
    }
 
    // 11.14 Comma Operator
 
    function parseExpression() {
        var expr, startToken = lookahead, expressions;
 
        expr = isolateCoverGrammar(parseAssignmentExpression);
 
        if (match(',')) {
            expressions = [expr];
 
            while (startIndex < length) {
                if (!match(',')) {
                    break;
                }
                lex();
                expressions.push(isolateCoverGrammar(parseAssignmentExpression));
            }
 
            expr = new WrappingNode(startToken).finishSequenceExpression(expressions);
        }
 
        return expr;
    }
 
    // 12.1 Block
 
    function parseStatementListItem() {
        if (lookahead.type === Token.Keyword) {
            switch (lookahead.value) {
            case 'export':
                if (sourceType !== 'module') {
                    tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration);
                }
                return parseExportDeclaration();
            case 'import':
                if (sourceType !== 'module') {
                    tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration);
                }
                return parseImportDeclaration();
            case 'const':
            case 'let':
                return parseLexicalDeclaration({inFor: false});
            case 'function':
                return parseFunctionDeclaration(new Node());
            case 'class':
                return parseClassDeclaration();
            }
        }
 
        return parseStatement();
    }
 
    function parseStatementList() {
        var list = [];
        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            list.push(parseStatementListItem());
        }
 
        return list;
    }
 
    function parseBlock() {
        var block, node = new Node();
 
        expect('{');
 
        block = parseStatementList();
 
        expect('}');
 
        return node.finishBlockStatement(block);
    }
 
    // 12.2 Variable Statement
 
    function parseVariableIdentifier() {
        var token, node = new Node();
 
        token = lex();
 
        if (token.type !== Token.Identifier) {
            if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {
                tolerateUnexpectedToken(token, Messages.StrictReservedWord);
            } else {
                throwUnexpectedToken(token);
            }
        }
 
        return node.finishIdentifier(token.value);
    }
 
    function parseVariableDeclaration() {
        var init = null, id, node = new Node();
 
        id = parsePattern();
 
        // 12.2.1
        if (strict && isRestrictedWord(id.name)) {
            tolerateError(Messages.StrictVarName);
        }
 
        if (match('=')) {
            lex();
            init = isolateCoverGrammar(parseAssignmentExpression);
        } else if (id.type !== Syntax.Identifier) {
            expect('=');
        }
 
        return node.finishVariableDeclarator(id, init);
    }
 
    function parseVariableDeclarationList() {
        var list = [];
 
        do {
            list.push(parseVariableDeclaration());
            if (!match(',')) {
                break;
            }
            lex();
        } while (startIndex < length);
 
        return list;
    }
 
    function parseVariableStatement(node) {
        var declarations;
 
        expectKeyword('var');
 
        declarations = parseVariableDeclarationList();
 
        consumeSemicolon();
 
        return node.finishVariableDeclaration(declarations);
    }
 
    function parseLexicalBinding(kind, options) {
        var init = null, id, node = new Node();
 
        id = parsePattern();
 
        // 12.2.1
        if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) {
            tolerateError(Messages.StrictVarName);
        }
 
        if (kind === 'const') {
            if (!matchKeyword('in')) {
                expect('=');
                init = isolateCoverGrammar(parseAssignmentExpression);
            }
        } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) {
            expect('=');
            init = isolateCoverGrammar(parseAssignmentExpression);
        }
 
        return node.finishVariableDeclarator(id, init);
    }
 
    function parseBindingList(kind, options) {
        var list = [];
 
        do {
            list.push(parseLexicalBinding(kind, options));
            if (!match(',')) {
                break;
            }
            lex();
        } while (startIndex < length);
 
        return list;
    }
 
    function parseLexicalDeclaration(options) {
        var kind, declarations, node = new Node();
 
        kind = lex().value;
        assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
 
        declarations = parseBindingList(kind, options);
 
        consumeSemicolon();
 
        return node.finishLexicalDeclaration(declarations, kind);
    }
 
    function parseRestElement() {
        var param, node = new Node();
 
        lex();
 
        if (match('{')) {
            throwError(Messages.ObjectPatternAsRestParameter);
        }
 
        param = parseVariableIdentifier();
 
        if (match('=')) {
            throwError(Messages.DefaultRestParameter);
        }
 
        if (!match(')')) {
            throwError(Messages.ParameterAfterRestParameter);
        }
 
        return node.finishRestElement(param);
    }
 
    // 12.3 Empty Statement
 
    function parseEmptyStatement(node) {
        expect(';');
        return node.finishEmptyStatement();
    }
 
    // 12.4 Expression Statement
 
    function parseExpressionStatement(node) {
        var expr = parseExpression();
        consumeSemicolon();
        return node.finishExpressionStatement(expr);
    }
 
    // 12.5 If statement
 
    function parseIfStatement(node) {
        var test, consequent, alternate;
 
        expectKeyword('if');
 
        expect('(');
 
        test = parseExpression();
 
        expect(')');
 
        consequent = parseStatement();
 
        if (matchKeyword('else')) {
            lex();
            alternate = parseStatement();
        } else {
            alternate = null;
        }
 
        return node.finishIfStatement(test, consequent, alternate);
    }
 
    // 12.6 Iteration Statements
 
    function parseDoWhileStatement(node) {
        var body, test, oldInIteration;
 
        expectKeyword('do');
 
        oldInIteration = state.inIteration;
        state.inIteration = true;
 
        body = parseStatement();
 
        state.inIteration = oldInIteration;
 
        expectKeyword('while');
 
        expect('(');
 
        test = parseExpression();
 
        expect(')');
 
        if (match(';')) {
            lex();
        }
 
        return node.finishDoWhileStatement(body, test);
    }
 
    function parseWhileStatement(node) {
        var test, body, oldInIteration;
 
        expectKeyword('while');
 
        expect('(');
 
        test = parseExpression();
 
        expect(')');
 
        oldInIteration = state.inIteration;
        state.inIteration = true;
 
        body = parseStatement();
 
        state.inIteration = oldInIteration;
 
        return node.finishWhileStatement(test, body);
    }
 
    function parseForStatement(node) {
        var init, initSeq, initStartToken, test, update, left, right, kind, declarations,
            body, oldInIteration, previousAllowIn = state.allowIn;
 
        init = test = update = null;
 
        expectKeyword('for');
 
        expect('(');
 
        if (match(';')) {
            lex();
        } else {
            if (matchKeyword('var')) {
                init = new Node();
                lex();
 
                state.allowIn = false;
                init = init.finishVariableDeclaration(parseVariableDeclarationList());
                state.allowIn = previousAllowIn;
 
                if (init.declarations.length === 1 && matchKeyword('in')) {
                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                } else {
                    expect(';');
                }
            } else if (matchKeyword('const') || matchKeyword('let')) {
                init = new Node();
                kind = lex().value;
 
                state.allowIn = false;
                declarations = parseBindingList(kind, {inFor: true});
                state.allowIn = previousAllowIn;
 
                if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) {
                    init = init.finishLexicalDeclaration(declarations, kind);
                    lex();
                    left = init;
                    right = parseExpression();
                    init = null;
                } else {
                    consumeSemicolon();
                    init = init.finishLexicalDeclaration(declarations, kind);
                }
            } else {
                initStartToken = lookahead;
                state.allowIn = false;
                init = inheritCoverGrammar(parseAssignmentExpression);
                state.allowIn = previousAllowIn;
 
                if (matchKeyword('in')) {
                    if (!isAssignmentTarget) {
                        tolerateError(Messages.InvalidLHSInForIn);
                    }
 
                    lex();
                    reinterpretExpressionAsPattern(init);
                    left = init;
                    right = parseExpression();
                    init = null;
                } else {
                    if (match(',')) {
                        initSeq = [init];
                        while (match(',')) {
                            lex();
                            initSeq.push(isolateCoverGrammar(parseAssignmentExpression));
                        }
                        init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq);
                    }
                    expect(';');
                }
            }
        }
 
        if (typeof left === 'undefined') {
 
            if (!match(';')) {
                test = parseExpression();
            }
            expect(';');
 
            if (!match(')')) {
                update = parseExpression();
            }
        }
 
        expect(')');
 
        oldInIteration = state.inIteration;
        state.inIteration = true;
 
        body = isolateCoverGrammar(parseStatement);
 
        state.inIteration = oldInIteration;
 
        return (typeof left === 'undefined') ?
                node.finishForStatement(init, test, update, body) :
                node.finishForInStatement(left, right, body);
    }
 
    // 12.7 The continue statement
 
    function parseContinueStatement(node) {
        var label = null, key;
 
        expectKeyword('continue');
 
        // Optimize the most common form: 'continue;'.
        if (source.charCodeAt(startIndex) === 0x3B) {
            lex();
 
            if (!state.inIteration) {
                throwError(Messages.IllegalContinue);
            }
 
            return node.finishContinueStatement(null);
        }
 
        if (hasLineTerminator) {
            if (!state.inIteration) {
                throwError(Messages.IllegalContinue);
            }
 
            return node.finishContinueStatement(null);
        }
 
        if (lookahead.type === Token.Identifier) {
            label = parseVariableIdentifier();
 
            key = '$' + label.name;
            if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError(Messages.UnknownLabel, label.name);
            }
        }
 
        consumeSemicolon();
 
        if (label === null && !state.inIteration) {
            throwError(Messages.IllegalContinue);
        }
 
        return node.finishContinueStatement(label);
    }
 
    // 12.8 The break statement
 
    function parseBreakStatement(node) {
        var label = null, key;
 
        expectKeyword('break');
 
        // Catch the very common case first: immediately a semicolon (U+003B).
        if (source.charCodeAt(lastIndex) === 0x3B) {
            lex();
 
            if (!(state.inIteration || state.inSwitch)) {
                throwError(Messages.IllegalBreak);
            }
 
            return node.finishBreakStatement(null);
        }
 
        if (hasLineTerminator) {
            if (!(state.inIteration || state.inSwitch)) {
                throwError(Messages.IllegalBreak);
            }
 
            return node.finishBreakStatement(null);
        }
 
        if (lookahead.type === Token.Identifier) {
            label = parseVariableIdentifier();
 
            key = '$' + label.name;
            if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError(Messages.UnknownLabel, label.name);
            }
        }
 
        consumeSemicolon();
 
        if (label === null && !(state.inIteration || state.inSwitch)) {
            throwError(Messages.IllegalBreak);
        }
 
        return node.finishBreakStatement(label);
    }
 
    // 12.9 The return statement
 
    function parseReturnStatement(node) {
        var argument = null;
 
        expectKeyword('return');
 
        if (!state.inFunctionBody) {
            tolerateError(Messages.IllegalReturn);
        }
 
        // 'return' followed by a space and an identifier is very common.
        if (source.charCodeAt(lastIndex) === 0x20) {
            if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) {
                argument = parseExpression();
                consumeSemicolon();
                return node.finishReturnStatement(argument);
            }
        }
 
        if (hasLineTerminator) {
            // HACK
            return node.finishReturnStatement(null);
        }
 
        if (!match(';')) {
            if (!match('}') && lookahead.type !== Token.EOF) {
                argument = parseExpression();
            }
        }
 
        consumeSemicolon();
 
        return node.finishReturnStatement(argument);
    }
 
    // 12.10 The with statement
 
    function parseWithStatement(node) {
        var object, body;
 
        if (strict) {
            tolerateError(Messages.StrictModeWith);
        }
 
        expectKeyword('with');
 
        expect('(');
 
        object = parseExpression();
 
        expect(')');
 
        body = parseStatement();
 
        return node.finishWithStatement(object, body);
    }
 
    // 12.10 The swith statement
 
    function parseSwitchCase() {
        var test, consequent = [], statement, node = new Node();
 
        if (matchKeyword('default')) {
            lex();
            test = null;
        } else {
            expectKeyword('case');
            test = parseExpression();
        }
        expect(':');
 
        while (startIndex < length) {
            if (match('}') || matchKeyword('default') || matchKeyword('case')) {
                break;
            }
            statement = parseStatementListItem();
            consequent.push(statement);
        }
 
        return node.finishSwitchCase(test, consequent);
    }
 
    function parseSwitchStatement(node) {
        var discriminant, cases, clause, oldInSwitch, defaultFound;
 
        expectKeyword('switch');
 
        expect('(');
 
        discriminant = parseExpression();
 
        expect(')');
 
        expect('{');
 
        cases = [];
 
        if (match('}')) {
            lex();
            return node.finishSwitchStatement(discriminant, cases);
        }
 
        oldInSwitch = state.inSwitch;
        state.inSwitch = true;
        defaultFound = false;
 
        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            clause = parseSwitchCase();
            if (clause.test === null) {
                if (defaultFound) {
                    throwError(Messages.MultipleDefaultsInSwitch);
                }
                defaultFound = true;
            }
            cases.push(clause);
        }
 
        state.inSwitch = oldInSwitch;
 
        expect('}');
 
        return node.finishSwitchStatement(discriminant, cases);
    }
 
    // 12.13 The throw statement
 
    function parseThrowStatement(node) {
        var argument;
 
        expectKeyword('throw');
 
        if (hasLineTerminator) {
            throwError(Messages.NewlineAfterThrow);
        }
 
        argument = parseExpression();
 
        consumeSemicolon();
 
        return node.finishThrowStatement(argument);
    }
 
    // 12.14 The try statement
 
    function parseCatchClause() {
        var param, body, node = new Node();
 
        expectKeyword('catch');
 
        expect('(');
        if (match(')')) {
            throwUnexpectedToken(lookahead);
        }
 
        param = parsePattern();
 
        // 12.14.1
        if (strict && isRestrictedWord(param.name)) {
            tolerateError(Messages.StrictCatchVariable);
        }
 
        expect(')');
        body = parseBlock();
        return node.finishCatchClause(param, body);
    }
 
    function parseTryStatement(node) {
        var block, handler = null, finalizer = null;
 
        expectKeyword('try');
 
        block = parseBlock();
 
        if (matchKeyword('catch')) {
            handler = parseCatchClause();
        }
 
        if (matchKeyword('finally')) {
            lex();
            finalizer = parseBlock();
        }
 
        if (!handler && !finalizer) {
            throwError(Messages.NoCatchOrFinally);
        }
 
        return node.finishTryStatement(block, handler, finalizer);
    }
 
    // 12.15 The debugger statement
 
    function parseDebuggerStatement(node) {
        expectKeyword('debugger');
 
        consumeSemicolon();
 
        return node.finishDebuggerStatement();
    }
 
    // 12 Statements
 
    function parseStatement() {
        var type = lookahead.type,
            expr,
            labeledBody,
            key,
            node;
 
        if (type === Token.EOF) {
            throwUnexpectedToken(lookahead);
        }
 
        if (type === Token.Punctuator && lookahead.value === '{') {
            return parseBlock();
        }
        isAssignmentTarget = isBindingElement = true;
        node = new Node();
 
        if (type === Token.Punctuator) {
            switch (lookahead.value) {
            case ';':
                return parseEmptyStatement(node);
            case '(':
                return parseExpressionStatement(node);
            default:
                break;
            }
        } else if (type === Token.Keyword) {
            switch (lookahead.value) {
            case 'break':
                return parseBreakStatement(node);
            case 'continue':
                return parseContinueStatement(node);
            case 'debugger':
                return parseDebuggerStatement(node);
            case 'do':
                return parseDoWhileStatement(node);
            case 'for':
                return parseForStatement(node);
            case 'function':
                return parseFunctionDeclaration(node);
            case 'if':
                return parseIfStatement(node);
            case 'return':
                return parseReturnStatement(node);
            case 'switch':
                return parseSwitchStatement(node);
            case 'throw':
                return parseThrowStatement(node);
            case 'try':
                return parseTryStatement(node);
            case 'var':
                return parseVariableStatement(node);
            case 'while':
                return parseWhileStatement(node);
            case 'with':
                return parseWithStatement(node);
            default:
                break;
            }
        }
 
        expr = parseExpression();
 
        // 12.12 Labelled Statements
        if ((expr.type === Syntax.Identifier) && match(':')) {
            lex();
 
            key = '$' + expr.name;
            if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) {
                throwError(Messages.Redeclaration, 'Label', expr.name);
            }
 
            state.labelSet[key] = true;
            labeledBody = parseStatement();
            delete state.labelSet[key];
            return node.finishLabeledStatement(expr, labeledBody);
        }
 
        consumeSemicolon();
 
        return node.finishExpressionStatement(expr);
    }
 
    // 13 Function Definition
 
    function parseFunctionSourceElements() {
        var statement, body = [], token, directive, firstRestricted,
            oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
            node = new Node();
 
        expect('{');
 
        while (startIndex < length) {
            if (lookahead.type !== Token.StringLiteral) {
                break;
            }
            token = lookahead;
 
            statement = parseStatementListItem();
            body.push(statement);
            if (statement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }
 
        oldLabelSet = state.labelSet;
        oldInIteration = state.inIteration;
        oldInSwitch = state.inSwitch;
        oldInFunctionBody = state.inFunctionBody;
        oldParenthesisCount = state.parenthesizedCount;
 
        state.labelSet = {};
        state.inIteration = false;
        state.inSwitch = false;
        state.inFunctionBody = true;
        state.parenthesizedCount = 0;
 
        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            body.push(parseStatementListItem());
        }
 
        expect('}');
 
        state.labelSet = oldLabelSet;
        state.inIteration = oldInIteration;
        state.inSwitch = oldInSwitch;
        state.inFunctionBody = oldInFunctionBody;
        state.parenthesizedCount = oldParenthesisCount;
 
        return node.finishBlockStatement(body);
    }
 
    function validateParam(options, param, name) {
        var key = '$' + name;
        if (strict) {
            if (isRestrictedWord(name)) {
                options.stricted = param;
                options.message = Messages.StrictParamName;
            }
            if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                options.stricted = param;
                options.message = Messages.StrictParamDupe;
            }
        } else if (!options.firstRestricted) {
            if (isRestrictedWord(name)) {
                options.firstRestricted = param;
                options.message = Messages.StrictParamName;
            } else if (isStrictModeReservedWord(name)) {
                options.firstRestricted = param;
                options.message = Messages.StrictReservedWord;
            } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                options.firstRestricted = param;
                options.message = Messages.StrictParamDupe;
            }
        }
        options.paramSet[key] = true;
    }
 
    function parseParam(options) {
        var token, param, def;
 
        token = lookahead;
        if (token.value === '...') {
            param = parseRestElement();
            validateParam(options, param.argument, param.argument.name);
            options.params.push(param);
            options.defaults.push(null);
            return false;
        }
 
        param = parsePatternWithDefault();
        validateParam(options, token, token.value);
 
        if (param.type === Syntax.AssignmentPattern) {
            def = param.right;
            param = param.left;
            ++options.defaultCount;
        }
 
        options.params.push(param);
        options.defaults.push(def);
 
        return !match(')');
    }
 
    function parseParams(firstRestricted) {
        var options;
 
        options = {
            params: [],
            defaultCount: 0,
            defaults: [],
            firstRestricted: firstRestricted
        };
 
        expect('(');
 
        if (!match(')')) {
            options.paramSet = {};
            while (startIndex < length) {
                if (!parseParam(options)) {
                    break;
                }
                expect(',');
            }
        }
 
        expect(')');
 
        if (options.defaultCount === 0) {
            options.defaults = [];
        }
 
        return {
            params: options.params,
            defaults: options.defaults,
            stricted: options.stricted,
            firstRestricted: options.firstRestricted,
            message: options.message
        };
    }
 
    function parseFunctionDeclaration(node, identifierIsOptional) {
        var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict;
 
        expectKeyword('function');
        if (!identifierIsOptional || !match('(')) {
            token = lookahead;
            id = parseVariableIdentifier();
            if (strict) {
                if (isRestrictedWord(token.value)) {
                    tolerateUnexpectedToken(token, Messages.StrictFunctionName);
                }
            } else {
                if (isRestrictedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictFunctionName;
                } else if (isStrictModeReservedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictReservedWord;
                }
            }
        }
 
        tmp = parseParams(firstRestricted);
        params = tmp.params;
        defaults = tmp.defaults;
        stricted = tmp.stricted;
        firstRestricted = tmp.firstRestricted;
        if (tmp.message) {
            message = tmp.message;
        }
 
        previousStrict = strict;
        body = parseFunctionSourceElements();
        if (strict && firstRestricted) {
            throwUnexpectedToken(firstRestricted, message);
        }
        if (strict && stricted) {
            tolerateUnexpectedToken(stricted, message);
        }
        strict = previousStrict;
 
        return node.finishFunctionDeclaration(id, params, defaults, body);
    }
 
    function parseFunctionExpression() {
        var token, id = null, stricted, firstRestricted, message, tmp,
            params = [], defaults = [], body, previousStrict, node = new Node();
 
        expectKeyword('function');
 
        if (!match('(')) {
            token = lookahead;
            id = parseVariableIdentifier();
            if (strict) {
                if (isRestrictedWord(token.value)) {
                    tolerateUnexpectedToken(token, Messages.StrictFunctionName);
                }
            } else {
                if (isRestrictedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictFunctionName;
                } else if (isStrictModeReservedWord(token.value)) {
                    firstRestricted = token;
                    message = Messages.StrictReservedWord;
                }
            }
        }
 
        tmp = parseParams(firstRestricted);
        params = tmp.params;
        defaults = tmp.defaults;
        stricted = tmp.stricted;
        firstRestricted = tmp.firstRestricted;
        if (tmp.message) {
            message = tmp.message;
        }
 
        previousStrict = strict;
        body = parseFunctionSourceElements();
        if (strict && firstRestricted) {
            throwUnexpectedToken(firstRestricted, message);
        }
        if (strict && stricted) {
            tolerateUnexpectedToken(stricted, message);
        }
        strict = previousStrict;
 
        return node.finishFunctionExpression(id, params, defaults, body);
    }
 
 
    function parseClassBody() {
        var classBody, token, isStatic, hasConstructor = false, body, method, computed, key;
 
        classBody = new Node();
 
        expect('{');
        body = [];
        while (!match('}')) {
            if (match(';')) {
                lex();
            } else {
                method = new Node();
                token = lookahead;
                isStatic = false;
                computed = match('[');
                key = parseObjectPropertyKey();
                if (key.name === 'static' && lookaheadPropertyName()) {
                    token = lookahead;
                    isStatic = true;
                    computed = match('[');
                    key = parseObjectPropertyKey();
                }
                method = tryParseMethodDefinition(token, key, computed, method);
                if (method) {
                    method['static'] = isStatic;
                    if (method.kind === 'init') {
                        method.kind = 'method';
                    }
                    if (!isStatic) {
                        if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') {
                            if (method.kind !== 'method' || !method.method || method.value.generator) {
                                throwUnexpectedToken(token, Messages.ConstructorSpecialMethod);
                            }
                            if (hasConstructor) {
                                throwUnexpectedToken(token, Messages.DuplicateConstructor);
                            } else {
                                hasConstructor = true;
                            }
                            method.kind = 'constructor';
                        }
                    } else {
                        if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') {
                            throwUnexpectedToken(token, Messages.StaticPrototype);
                        }
                    }
                    method.type = Syntax.MethodDefinition;
                    delete method.method;
                    delete method.shorthand;
                    body.push(method);
                } else {
                    throwUnexpectedToken(lookahead);
                }
            }
        }
        lex();
        return classBody.finishClassBody(body);
    }
 
    function parseClassDeclaration(identifierIsOptional) {
        var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
        strict = true;
 
        expectKeyword('class');
 
        if (!identifierIsOptional || lookahead.type === Token.Identifier) {
            id = parseVariableIdentifier();
        }
 
        if (matchKeyword('extends')) {
            lex();
            superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
        }
        classBody = parseClassBody();
        strict = previousStrict;
 
        return classNode.finishClassDeclaration(id, superClass, classBody);
    }
 
    function parseClassExpression() {
        var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
        strict = true;
 
        expectKeyword('class');
 
        if (lookahead.type === Token.Identifier) {
            id = parseVariableIdentifier();
        }
 
        if (matchKeyword('extends')) {
            lex();
            superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall);
        }
        classBody = parseClassBody();
        strict = previousStrict;
 
        return classNode.finishClassExpression(id, superClass, classBody);
    }
 
    // Modules grammar from:
    // people.mozilla.org/~jorendorff/es6-draft.html
 
    function parseModuleSpecifier() {
        var node = new Node();
 
        if (lookahead.type !== Token.StringLiteral) {
            throwError(Messages.InvalidModuleSpecifier);
        }
        return node.finishLiteral(lex());
    }
 
    function parseExportSpecifier() {
        var exported, local, node = new Node(), def;
        if (matchKeyword('default')) {
            // export {default} from 'something';
            def = new Node();
            lex();
            local = def.finishIdentifier('default');
        } else {
            local = parseVariableIdentifier();
        }
        if (matchContextualKeyword('as')) {
            lex();
            exported = parseNonComputedProperty();
        }
        return node.finishExportSpecifier(local, exported);
    }
 
    function parseExportNamedDeclaration(node) {
        var declaration = null,
            isExportFromIdentifier,
            src = null, specifiers = [];
 
        // non-default export
        if (lookahead.type === Token.Keyword) {
            // covers:
            // export var f = 1;
            switch (lookahead.value) {
                case 'let':
                case 'const':
                case 'var':
                case 'class':
                case 'function':
                    declaration = parseStatementListItem();
                    return node.finishExportNamedDeclaration(declaration, specifiers, null);
            }
        }
 
        expect('{');
        if (!match('}')) {
            do {
                isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
                specifiers.push(parseExportSpecifier());
            } while (match(',') && lex());
        }
        expect('}');
 
        if (matchContextualKeyword('from')) {
            // covering:
            // export {default} from 'foo';
            // export {foo} from 'foo';
            lex();
            src = parseModuleSpecifier();
            consumeSemicolon();
        } else if (isExportFromIdentifier) {
            // covering:
            // export {default}; // missing fromClause
            throwError(lookahead.value ?
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
        } else {
            // cover
            // export {foo};
            consumeSemicolon();
        }
        return node.finishExportNamedDeclaration(declaration, specifiers, src);
    }
 
    function parseExportDefaultDeclaration(node) {
        var declaration = null,
            expression = null;
 
        // covers:
        // export default ...
        expectKeyword('default');
 
        if (matchKeyword('function')) {
            // covers:
            // export default function foo () {}
            // export default function () {}
            declaration = parseFunctionDeclaration(new Node(), true);
            return node.finishExportDefaultDeclaration(declaration);
        }
        if (matchKeyword('class')) {
            declaration = parseClassDeclaration(true);
            return node.finishExportDefaultDeclaration(declaration);
        }
 
        if (matchContextualKeyword('from')) {
            throwError(Messages.UnexpectedToken, lookahead.value);
        }
 
        // covers:
        // export default {};
        // export default [];
        // export default (1 + 2);
        if (match('{')) {
            expression = parseObjectInitialiser();
        } else if (match('[')) {
            expression = parseArrayInitialiser();
        } else {
            expression = parseAssignmentExpression();
        }
        consumeSemicolon();
        return node.finishExportDefaultDeclaration(expression);
    }
 
    function parseExportAllDeclaration(node) {
        var src;
 
        // covers:
        // export * from 'foo';
        expect('*');
        if (!matchContextualKeyword('from')) {
            throwError(lookahead.value ?
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
        }
        lex();
        src = parseModuleSpecifier();
        consumeSemicolon();
 
        return node.finishExportAllDeclaration(src);
    }
 
    function parseExportDeclaration() {
        var node = new Node();
        if (state.inFunctionBody) {
            throwError(Messages.IllegalExportDeclaration);
        }
 
        expectKeyword('export');
 
        if (matchKeyword('default')) {
            return parseExportDefaultDeclaration(node);
        }
        if (match('*')) {
            return parseExportAllDeclaration(node);
        }
        return parseExportNamedDeclaration(node);
    }
 
    function parseImportSpecifier() {
        // import {<foo as bar>} ...;
        var local, imported, node = new Node();
 
        imported = parseNonComputedProperty();
        if (matchContextualKeyword('as')) {
            lex();
            local = parseVariableIdentifier();
        }
 
        return node.finishImportSpecifier(local, imported);
    }
 
    function parseNamedImports() {
        var specifiers = [];
        // {foo, bar as bas}
        expect('{');
        if (!match('}')) {
            do {
                specifiers.push(parseImportSpecifier());
            } while (match(',') && lex());
        }
        expect('}');
        return specifiers;
    }
 
    function parseImportDefaultSpecifier() {
        // import <foo> ...;
        var local, node = new Node();
 
        local = parseNonComputedProperty();
 
        return node.finishImportDefaultSpecifier(local);
    }
 
    function parseImportNamespaceSpecifier() {
        // import <* as foo> ...;
        var local, node = new Node();
 
        expect('*');
        if (!matchContextualKeyword('as')) {
            throwError(Messages.NoAsAfterImportNamespace);
        }
        lex();
        local = parseNonComputedProperty();
 
        return node.finishImportNamespaceSpecifier(local);
    }
 
    function parseImportDeclaration() {
        var specifiers, src, node = new Node();
 
        if (state.inFunctionBody) {
            throwError(Messages.IllegalImportDeclaration);
        }
 
        expectKeyword('import');
        specifiers = [];
 
        if (lookahead.type === Token.StringLiteral) {
            // covers:
            // import 'foo';
            src = parseModuleSpecifier();
            consumeSemicolon();
            return node.finishImportDeclaration(specifiers, src);
        }
 
        if (!matchKeyword('default') && isIdentifierName(lookahead)) {
            // covers:
            // import foo
            // import foo, ...
            specifiers.push(parseImportDefaultSpecifier());
            if (match(',')) {
                lex();
            }
        }
        if (match('*')) {
            // covers:
            // import foo, * as foo
            // import * as foo
            specifiers.push(parseImportNamespaceSpecifier());
        } else if (match('{')) {
            // covers:
            // import foo, {bar}
            // import {bar}
            specifiers = specifiers.concat(parseNamedImports());
        }
 
        if (!matchContextualKeyword('from')) {
            throwError(lookahead.value ?
                    Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
        }
        lex();
        src = parseModuleSpecifier();
        consumeSemicolon();
 
        return node.finishImportDeclaration(specifiers, src);
    }
 
    // 14 Program
 
    function parseScriptBody() {
        var statement, body = [], token, directive, firstRestricted;
 
        while (startIndex < length) {
            token = lookahead;
            if (token.type !== Token.StringLiteral) {
                break;
            }
 
            statement = parseStatementListItem();
            body.push(statement);
            if (statement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }
 
        while (startIndex < length) {
            statement = parseStatementListItem();
            /* istanbul ignore if */
            if (typeof statement === 'undefined') {
                break;
            }
            body.push(statement);
        }
        return body;
    }
 
    function parseProgram() {
        var body, node;
 
        peek();
        node = new Node();
 
        body = parseScriptBody();
        return node.finishProgram(body);
    }
 
    function filterTokenLocation() {
        var i, entry, token, tokens = [];
 
        for (i = 0; i < extra.tokens.length; ++i) {
            entry = extra.tokens[i];
            token = {
                type: entry.type,
                value: entry.value
            };
            if (entry.regex) {
                token.regex = {
                    pattern: entry.regex.pattern,
                    flags: entry.regex.flags
                };
            }
            if (extra.range) {
                token.range = entry.range;
            }
            if (extra.loc) {
                token.loc = entry.loc;
            }
            tokens.push(token);
        }
 
        extra.tokens = tokens;
    }
 
    function tokenize(code, options) {
        var toString,
            tokens;
 
        toString = String;
        if (typeof code !== 'string' && !(code instanceof String)) {
            code = toString(code);
        }
 
        source = code;
        index = 0;
        lineNumber = (source.length > 0) ? 1 : 0;
        lineStart = 0;
        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;
        length = source.length;
        lookahead = null;
        state = {
            allowIn: true,
            labelSet: {},
            inFunctionBody: false,
            inIteration: false,
            inSwitch: false,
            lastCommentStart: -1,
            curlyStack: []
        };
 
        extra = {};
 
        // Options matching.
        options = options || {};
 
        // Of course we collect tokens here.
        options.tokens = true;
        extra.tokens = [];
        extra.tokenize = true;
        // The following two fields are necessary to compute the Regex tokens.
        extra.openParenToken = -1;
        extra.openCurlyToken = -1;
 
        extra.range = (typeof options.range === 'boolean') && options.range;
        extra.loc = (typeof options.loc === 'boolean') && options.loc;
 
        if (typeof options.comment === 'boolean' && options.comment) {
            extra.comments = [];
        }
        if (typeof options.tolerant === 'boolean' && options.tolerant) {
            extra.errors = [];
        }
 
        try {
            peek();
            if (lookahead.type === Token.EOF) {
                return extra.tokens;
            }
 
            lex();
            while (lookahead.type !== Token.EOF) {
                try {
                    lex();
                } catch (lexError) {
                    if (extra.errors) {
                        recordError(lexError);
                        // We have to break on the first error
                        // to avoid infinite loops.
                        break;
                    } else {
                        throw lexError;
                    }
                }
            }
 
            filterTokenLocation();
            tokens = extra.tokens;
            if (typeof extra.comments !== 'undefined') {
                tokens.comments = extra.comments;
            }
            if (typeof extra.errors !== 'undefined') {
                tokens.errors = extra.errors;
            }
        } catch (e) {
            throw e;
        } finally {
            extra = {};
        }
        return tokens;
    }
 
    function parse(code, options) {
        var program, toString;
 
        toString = String;
        if (typeof code !== 'string' && !(code instanceof String)) {
            code = toString(code);
        }
 
        source = code;
        index = 0;
        lineNumber = (source.length > 0) ? 1 : 0;
        lineStart = 0;
        startIndex = index;
        startLineNumber = lineNumber;
        startLineStart = lineStart;
        length = source.length;
        lookahead = null;
        state = {
            allowIn: true,
            labelSet: {},
            inFunctionBody: false,
            inIteration: false,
            inSwitch: false,
            lastCommentStart: -1,
            curlyStack: []
        };
        sourceType = 'script';
        strict = false;
 
        extra = {};
        if (typeof options !== 'undefined') {
            extra.range = (typeof options.range === 'boolean') && options.range;
            extra.loc = (typeof options.loc === 'boolean') && options.loc;
            extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
 
            if (extra.loc && options.source !== null && options.source !== undefined) {
                extra.source = toString(options.source);
            }
 
            if (typeof options.tokens === 'boolean' && options.tokens) {
                extra.tokens = [];
            }
            if (typeof options.comment === 'boolean' && options.comment) {
                extra.comments = [];
            }
            if (typeof options.tolerant === 'boolean' && options.tolerant) {
                extra.errors = [];
            }
            if (extra.attachComment) {
                extra.range = true;
                extra.comments = [];
                extra.bottomRightStack = [];
                extra.trailingComments = [];
                extra.leadingComments = [];
            }
            if (options.sourceType === 'module') {
                // very restrictive condition for now
                sourceType = options.sourceType;
                strict = true;
            }
        }
 
        try {
            program = parseProgram();
            if (typeof extra.comments !== 'undefined') {
                program.comments = extra.comments;
            }
            if (typeof extra.tokens !== 'undefined') {
                filterTokenLocation();
                program.tokens = extra.tokens;
            }
            if (typeof extra.errors !== 'undefined') {
                program.errors = extra.errors;
            }
        } catch (e) {
            throw e;
        } finally {
            extra = {};
        }
 
        return program;
    }
 
    // Sync with *.json manifests.
    exports.version = '2.2.0';
 
    exports.tokenize = tokenize;
 
    exports.parse = parse;
 
    // Deep copy.
    /* istanbul ignore next */
    exports.Syntax = (function () {
        var name, types = {};
 
        Eif (typeof Object.create === 'function') {
            types = Object.create(null);
        }
 
        for (name in Syntax) {
            Eif (Syntax.hasOwnProperty(name)) {
                types[name] = Syntax[name];
            }
        }
 
        Eif (typeof Object.freeze === 'function') {
            Object.freeze(types);
        }
 
        return types;
    }());
 
}));
/* vim: set sw=4 ts=4 et tw=80 : */
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/lunr/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/lunr/

Statements: 27.18% (153 / 563)      Branches: 6.67% (14 / 210)      Functions: 21.65% (21 / 97)      Lines: 29.49% (151 / 512)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/lunr/
File Statements Branches Functions Lines
lunr.js 27.18% (153 / 563) 6.67% (14 / 210) 21.65% (21 / 97) 29.49% (151 / 512)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/lunr/lunr.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/lunr/lunr.js

Statements: 27.18% (153 / 563)      Branches: 6.67% (14 / 210)      Functions: 21.65% (21 / 97)      Lines: 29.49% (151 / 512)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918              1                                                                         1 1   1           1   1     1                 1               1 1                                 1 1                       1 1       1   1 3 3                     1                                   1                                 1 3                               1                                                                                 1 1     1                             1 3       3 3                   1 3   3                               1                                               1 1   1 3 3                           1                                           1                                 1                                 1                                               1                       1                                   1                                 1                         1                                                                       1                                           1                                                         1                           1 2 2                   1                               1                                   1                                 1                             1                       1                                                                   1                                                       1                                                                     1                                 1                                           1                             1 1 1 1 1 1 1 1   1   1                           1 1 1                   1                           1                                                                       1 4     4 4                               1                                       1                                                                                                       1                                                                         1                                 1                                                                           1                                                                                                                                               1                                           1                                                                           1                                 1 1 1                   1                                     1                       1                     1                   1                         1                                           1 1                                                                                       1 1 1 1   1 1 1 1 1 1 1 1   1 1   1   1 1   1 1 1   1                                                                                                                                                                                                                                                               1     1                                   1       1 1 1                                                                                                                                                                                                                                                     1                                       1           1                         1 1 1                   1                                           1                                                   1                                                   1                                                 1       1                               1                                       1                                             1                       1 1     1           1                     1        
/**
 * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 0.5.9
 * Copyright (C) 2015 Oliver Nightingale
 * MIT Licensed
 * @license
 */
 
(function(){
 
/**
 * Convenience function for instantiating a new lunr index and configuring it
 * with the default pipeline functions and the passed config function.
 *
 * When using this convenience function a new index will be created with the
 * following functions already in the pipeline:
 *
 * lunr.StopWordFilter - filters out any stop words before they enter the
 * index
 *
 * lunr.stemmer - stems the tokens before entering the index.
 *
 * Example:
 *
 *     var idx = lunr(function () {
 *       this.field('title', 10)
 *       this.field('tags', 100)
 *       this.field('body')
 *       
 *       this.ref('cid')
 *       
 *       this.pipeline.add(function () {
 *         // some custom pipeline function
 *       })
 *       
 *     })
 *
 * @param {Function} config A function that will be called with the new instance
 * of the lunr.Index as both its context and first parameter. It can be used to
 * customize the instance of new lunr.Index.
 * @namespace
 * @module
 * @returns {lunr.Index}
 *
 */
var lunr = function (config) {
  var idx = new lunr.Index
 
  idx.pipeline.add(
    lunr.trimmer,
    lunr.stopWordFilter,
    lunr.stemmer
  )
 
  Eif (config) config.call(idx, idx)
 
  return idx
}
 
lunr.version = "0.5.9"
/*!
 * lunr.utils
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * A namespace containing utils for the rest of the lunr library
 */
lunr.utils = {}
 
/**
 * Print a warning message to the console.
 *
 * @param {String} message The message to be printed.
 * @memberOf Utils
 */
lunr.utils.warn = (function (global) {
  return function (message) {
    if (global.console && console.warn) {
      console.warn(message)
    }
  }
})(this)
 
/*!
 * lunr.EventEmitter
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers and triggering events and their handlers.
 *
 * @constructor
 */
lunr.EventEmitter = function () {
  this.events = {}
}
 
/**
 * Binds a handler function to a specific event(s).
 *
 * Can bind a single function to many different events in one call.
 *
 * @param {String} [eventName] The name(s) of events to bind this function to.
 * @param {Function} handler The function to call when an event is fired.
 * @memberOf EventEmitter
 */
lunr.EventEmitter.prototype.addListener = function () {
  var args = Array.prototype.slice.call(arguments),
      fn = args.pop(),
      names = args
 
  Iif (typeof fn !== "function") throw new TypeError ("last argument must be a function")
 
  names.forEach(function (name) {
    Eif (!this.hasHandler(name)) this.events[name] = []
    this.events[name].push(fn)
  }, this)
}
 
/**
 * Removes a handler function from a specific event.
 *
 * @param {String} eventName The name of the event to remove this function from.
 * @param {Function} handler The function to remove from an event.
 * @memberOf EventEmitter
 */
lunr.EventEmitter.prototype.removeListener = function (name, fn) {
  if (!this.hasHandler(name)) return
 
  var fnIndex = this.events[name].indexOf(fn)
  this.events[name].splice(fnIndex, 1)
 
  if (!this.events[name].length) delete this.events[name]
}
 
/**
 * Calls all functions bound to the given event.
 *
 * Additional data can be passed to the event handler as arguments to `emit`
 * after the event name.
 *
 * @param {String} eventName The name of the event to emit.
 * @memberOf EventEmitter
 */
lunr.EventEmitter.prototype.emit = function (name) {
  if (!this.hasHandler(name)) return
 
  var args = Array.prototype.slice.call(arguments, 1)
 
  this.events[name].forEach(function (fn) {
    fn.apply(undefined, args)
  })
}
 
/**
 * Checks whether a handler has ever been stored against an event.
 *
 * @param {String} eventName The name of the event to check.
 * @private
 * @memberOf EventEmitter
 */
lunr.EventEmitter.prototype.hasHandler = function (name) {
  return name in this.events
}
 
/*!
 * lunr.tokenizer
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * A function for splitting a string into tokens ready to be inserted into
 * the search index.
 *
 * @module
 * @param {String} obj The string to convert into tokens
 * @returns {Array}
 */
lunr.tokenizer = function (obj) {
  if (!arguments.length || obj == null || obj == undefined) return []
  if (Array.isArray(obj)) return obj.map(function (t) { return t.toLowerCase() })
 
  return obj.toString().trim().toLowerCase().split(/[\s\-]+/)
}
 
/*!
 * lunr.Pipeline
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.Pipelines maintain an ordered list of functions to be applied to all
 * tokens in documents entering the search index and queries being ran against
 * the index.
 *
 * An instance of lunr.Index created with the lunr shortcut will contain a
 * pipeline with a stop word filter and an English language stemmer. Extra
 * functions can be added before or after either of these functions or these
 * default functions can be removed.
 *
 * When run the pipeline will call each function in turn, passing a token, the
 * index of that token in the original list of all tokens and finally a list of
 * all the original tokens.
 *
 * The output of functions in the pipeline will be passed to the next function
 * in the pipeline. To exclude a token from entering the index the function
 * should return undefined, the rest of the pipeline will not be called with
 * this token.
 *
 * For serialisation of pipelines to work, all functions used in an instance of
 * a pipeline should be registered with lunr.Pipeline. Registered functions can
 * then be loaded. If trying to load a serialised pipeline that uses functions
 * that are not registered an error will be thrown.
 *
 * If not planning on serialising the pipeline then registering pipeline functions
 * is not necessary.
 *
 * @constructor
 */
lunr.Pipeline = function () {
  this._stack = []
}
 
lunr.Pipeline.registeredFunctions = {}
 
/**
 * Register a function with the pipeline.
 *
 * Functions that are used in the pipeline should be registered if the pipeline
 * needs to be serialised, or a serialised pipeline needs to be loaded.
 *
 * Registering a function does not add it to a pipeline, functions must still be
 * added to instances of the pipeline for them to be used when running a pipeline.
 *
 * @param {Function} fn The function to check for.
 * @param {String} label The label to register this function with
 * @memberOf Pipeline
 */
lunr.Pipeline.registerFunction = function (fn, label) {
  Iif (label in this.registeredFunctions) {
    lunr.utils.warn('Overwriting existing registered function: ' + label)
  }
 
  fn.label = label
  lunr.Pipeline.registeredFunctions[fn.label] = fn
}
 
/**
 * Warns if the function is not registered as a Pipeline function.
 *
 * @param {Function} fn The function to check for.
 * @private
 * @memberOf Pipeline
 */
lunr.Pipeline.warnIfFunctionNotRegistered = function (fn) {
  var isRegistered = fn.label && (fn.label in this.registeredFunctions)
 
  Iif (!isRegistered) {
    lunr.utils.warn('Function is not registered with pipeline. This may cause problems when serialising the index.\n', fn)
  }
}
 
/**
 * Loads a previously serialised pipeline.
 *
 * All functions to be loaded must already be registered with lunr.Pipeline.
 * If any function from the serialised data has not been registered then an
 * error will be thrown.
 *
 * @param {Object} serialised The serialised pipeline to load.
 * @returns {lunr.Pipeline}
 * @memberOf Pipeline
 */
lunr.Pipeline.load = function (serialised) {
  var pipeline = new lunr.Pipeline
 
  serialised.forEach(function (fnName) {
    var fn = lunr.Pipeline.registeredFunctions[fnName]
 
    if (fn) {
      pipeline.add(fn)
    } else {
      throw new Error('Cannot load un-registered function: ' + fnName)
    }
  })
 
  return pipeline
}
 
/**
 * Adds new functions to the end of the pipeline.
 *
 * Logs a warning if the function has not been registered.
 *
 * @param {Function} functions Any number of functions to add to the pipeline.
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.add = function () {
  var fns = Array.prototype.slice.call(arguments)
 
  fns.forEach(function (fn) {
    lunr.Pipeline.warnIfFunctionNotRegistered(fn)
    this._stack.push(fn)
  }, this)
}
 
/**
 * Adds a single function after a function that already exists in the
 * pipeline.
 *
 * Logs a warning if the function has not been registered.
 *
 * @param {Function} existingFn A function that already exists in the pipeline.
 * @param {Function} newFn The new function to add to the pipeline.
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.after = function (existingFn, newFn) {
  lunr.Pipeline.warnIfFunctionNotRegistered(newFn)
 
  var pos = this._stack.indexOf(existingFn)
  if (pos == -1) {
    throw new Error('Cannot find existingFn')
  }
 
  pos = pos + 1
  this._stack.splice(pos, 0, newFn)
}
 
/**
 * Adds a single function before a function that already exists in the
 * pipeline.
 *
 * Logs a warning if the function has not been registered.
 *
 * @param {Function} existingFn A function that already exists in the pipeline.
 * @param {Function} newFn The new function to add to the pipeline.
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.before = function (existingFn, newFn) {
  lunr.Pipeline.warnIfFunctionNotRegistered(newFn)
 
  var pos = this._stack.indexOf(existingFn)
  if (pos == -1) {
    throw new Error('Cannot find existingFn')
  }
 
  this._stack.splice(pos, 0, newFn)
}
 
/**
 * Removes a function from the pipeline.
 *
 * @param {Function} fn The function to remove from the pipeline.
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.remove = function (fn) {
  var pos = this._stack.indexOf(fn)
  if (pos == -1) {
    return
  }
 
  this._stack.splice(pos, 1)
}
 
/**
 * Runs the current list of functions that make up the pipeline against the
 * passed tokens.
 *
 * @param {Array} tokens The tokens to run through the pipeline.
 * @returns {Array}
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.run = function (tokens) {
  var out = [],
      tokenLength = tokens.length,
      stackLength = this._stack.length
 
  for (var i = 0; i < tokenLength; i++) {
    var token = tokens[i]
 
    for (var j = 0; j < stackLength; j++) {
      token = this._stack[j](token, i, tokens)
      if (token === void 0) break
    };
 
    if (token !== void 0) out.push(token)
  };
 
  return out
}
 
/**
 * Resets the pipeline by removing any existing processors.
 *
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.reset = function () {
  this._stack = []
}
 
/**
 * Returns a representation of the pipeline ready for serialisation.
 *
 * Logs a warning if the function has not been registered.
 *
 * @returns {Array}
 * @memberOf Pipeline
 */
lunr.Pipeline.prototype.toJSON = function () {
  return this._stack.map(function (fn) {
    lunr.Pipeline.warnIfFunctionNotRegistered(fn)
 
    return fn.label
  })
}
/*!
 * lunr.Vector
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.Vectors implement vector related operations for
 * a series of elements.
 *
 * @constructor
 */
lunr.Vector = function () {
  this._magnitude = null
  this.list = undefined
  this.length = 0
}
 
/**
 * lunr.Vector.Node is a simple struct for each node
 * in a lunr.Vector.
 *
 * @private
 * @param {Number} The index of the node in the vector.
 * @param {Object} The data at this node in the vector.
 * @param {lunr.Vector.Node} The node directly after this node in the vector.
 * @constructor
 * @memberOf Vector
 */
lunr.Vector.Node = function (idx, val, next) {
  this.idx = idx
  this.val = val
  this.next = next
}
 
/**
 * Inserts a new value at a position in a vector.
 *
 * @param {Number} The index at which to insert a value.
 * @param {Object} The object to insert in the vector.
 * @memberOf Vector.
 */
lunr.Vector.prototype.insert = function (idx, val) {
  this._magnitude = undefined;
  var list = this.list
 
  if (!list) {
    this.list = new lunr.Vector.Node (idx, val, list)
    return this.length++
  }
 
  if (idx < list.idx) {
    this.list = new lunr.Vector.Node (idx, val, list)
    return this.length++
  }
 
  var prev = list,
      next = list.next
 
  while (next != undefined) {
    if (idx < next.idx) {
      prev.next = new lunr.Vector.Node (idx, val, next)
      return this.length++
    }
 
    prev = next, next = next.next
  }
 
  prev.next = new lunr.Vector.Node (idx, val, next)
  return this.length++
}
 
/**
 * Calculates the magnitude of this vector.
 *
 * @returns {Number}
 * @memberOf Vector
 */
lunr.Vector.prototype.magnitude = function () {
  if (this._magnitude) return this._magnitude
  var node = this.list,
      sumOfSquares = 0,
      val
 
  while (node) {
    val = node.val
    sumOfSquares += val * val
    node = node.next
  }
 
  return this._magnitude = Math.sqrt(sumOfSquares)
}
 
/**
 * Calculates the dot product of this vector and another vector.
 *
 * @param {lunr.Vector} otherVector The vector to compute the dot product with.
 * @returns {Number}
 * @memberOf Vector
 */
lunr.Vector.prototype.dot = function (otherVector) {
  var node = this.list,
      otherNode = otherVector.list,
      dotProduct = 0
 
  while (node && otherNode) {
    if (node.idx < otherNode.idx) {
      node = node.next
    } else if (node.idx > otherNode.idx) {
      otherNode = otherNode.next
    } else {
      dotProduct += node.val * otherNode.val
      node = node.next
      otherNode = otherNode.next
    }
  }
 
  return dotProduct
}
 
/**
 * Calculates the cosine similarity between this vector and another
 * vector.
 *
 * @param {lunr.Vector} otherVector The other vector to calculate the
 * similarity with.
 * @returns {Number}
 * @memberOf Vector
 */
lunr.Vector.prototype.similarity = function (otherVector) {
  return this.dot(otherVector) / (this.magnitude() * otherVector.magnitude())
}
/*!
 * lunr.SortedSet
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.SortedSets are used to maintain an array of uniq values in a sorted
 * order.
 *
 * @constructor
 */
lunr.SortedSet = function () {
  this.length = 0
  this.elements = []
}
 
/**
 * Loads a previously serialised sorted set.
 *
 * @param {Array} serialisedData The serialised set to load.
 * @returns {lunr.SortedSet}
 * @memberOf SortedSet
 */
lunr.SortedSet.load = function (serialisedData) {
  var set = new this
 
  set.elements = serialisedData
  set.length = serialisedData.length
 
  return set
}
 
/**
 * Inserts new items into the set in the correct position to maintain the
 * order.
 *
 * @param {Object} The objects to add to this set.
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.add = function () {
  var i, element
 
  for (i = 0; i < arguments.length; i++) {
    element = arguments[i]
    if (~this.indexOf(element)) continue
    this.elements.splice(this.locationFor(element), 0, element)
  }
 
  this.length = this.elements.length
}
 
/**
 * Converts this sorted set into an array.
 *
 * @returns {Array}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.toArray = function () {
  return this.elements.slice()
}
 
/**
 * Creates a new array with the results of calling a provided function on every
 * element in this sorted set.
 *
 * Delegates to Array.prototype.map and has the same signature.
 *
 * @param {Function} fn The function that is called on each element of the
 * set.
 * @param {Object} ctx An optional object that can be used as the context
 * for the function fn.
 * @returns {Array}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.map = function (fn, ctx) {
  return this.elements.map(fn, ctx)
}
 
/**
 * Executes a provided function once per sorted set element.
 *
 * Delegates to Array.prototype.forEach and has the same signature.
 *
 * @param {Function} fn The function that is called on each element of the
 * set.
 * @param {Object} ctx An optional object that can be used as the context
 * @memberOf SortedSet
 * for the function fn.
 */
lunr.SortedSet.prototype.forEach = function (fn, ctx) {
  return this.elements.forEach(fn, ctx)
}
 
/**
 * Returns the index at which a given element can be found in the
 * sorted set, or -1 if it is not present.
 *
 * @param {Object} elem The object to locate in the sorted set.
 * @returns {Number}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.indexOf = function (elem) {
  var start = 0,
      end = this.elements.length,
      sectionLength = end - start,
      pivot = start + Math.floor(sectionLength / 2),
      pivotElem = this.elements[pivot]
 
  while (sectionLength > 1) {
    if (pivotElem === elem) return pivot
 
    if (pivotElem < elem) start = pivot
    if (pivotElem > elem) end = pivot
 
    sectionLength = end - start
    pivot = start + Math.floor(sectionLength / 2)
    pivotElem = this.elements[pivot]
  }
 
  if (pivotElem === elem) return pivot
 
  return -1
}
 
/**
 * Returns the position within the sorted set that an element should be
 * inserted at to maintain the current order of the set.
 *
 * This function assumes that the element to search for does not already exist
 * in the sorted set.
 *
 * @param {Object} elem The elem to find the position for in the set
 * @returns {Number}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.locationFor = function (elem) {
  var start = 0,
      end = this.elements.length,
      sectionLength = end - start,
      pivot = start + Math.floor(sectionLength / 2),
      pivotElem = this.elements[pivot]
 
  while (sectionLength > 1) {
    if (pivotElem < elem) start = pivot
    if (pivotElem > elem) end = pivot
 
    sectionLength = end - start
    pivot = start + Math.floor(sectionLength / 2)
    pivotElem = this.elements[pivot]
  }
 
  if (pivotElem > elem) return pivot
  if (pivotElem < elem) return pivot + 1
}
 
/**
 * Creates a new lunr.SortedSet that contains the elements in the intersection
 * of this set and the passed set.
 *
 * @param {lunr.SortedSet} otherSet The set to intersect with this set.
 * @returns {lunr.SortedSet}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.intersect = function (otherSet) {
  var intersectSet = new lunr.SortedSet,
      i = 0, j = 0,
      a_len = this.length, b_len = otherSet.length,
      a = this.elements, b = otherSet.elements
 
  while (true) {
    if (i > a_len - 1 || j > b_len - 1) break
 
    if (a[i] === b[j]) {
      intersectSet.add(a[i])
      i++, j++
      continue
    }
 
    if (a[i] < b[j]) {
      i++
      continue
    }
 
    if (a[i] > b[j]) {
      j++
      continue
    }
  };
 
  return intersectSet
}
 
/**
 * Makes a copy of this set
 *
 * @returns {lunr.SortedSet}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.clone = function () {
  var clone = new lunr.SortedSet
 
  clone.elements = this.toArray()
  clone.length = clone.elements.length
 
  return clone
}
 
/**
 * Creates a new lunr.SortedSet that contains the elements in the union
 * of this set and the passed set.
 *
 * @param {lunr.SortedSet} otherSet The set to union with this set.
 * @returns {lunr.SortedSet}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.union = function (otherSet) {
  var longSet, shortSet, unionSet
 
  if (this.length >= otherSet.length) {
    longSet = this, shortSet = otherSet
  } else {
    longSet = otherSet, shortSet = this
  }
 
  unionSet = longSet.clone()
 
  unionSet.add.apply(unionSet, shortSet.toArray())
 
  return unionSet
}
 
/**
 * Returns a representation of the sorted set ready for serialisation.
 *
 * @returns {Array}
 * @memberOf SortedSet
 */
lunr.SortedSet.prototype.toJSON = function () {
  return this.toArray()
}
/*!
 * lunr.Index
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.Index is object that manages a search index.  It contains the indexes
 * and stores all the tokens and document lookups.  It also provides the main
 * user facing API for the library.
 *
 * @constructor
 */
lunr.Index = function () {
  this._fields = []
  this._ref = 'id'
  this.pipeline = new lunr.Pipeline
  this.documentStore = new lunr.Store
  this.tokenStore = new lunr.TokenStore
  this.corpusTokens = new lunr.SortedSet
  this.eventEmitter =  new lunr.EventEmitter
 
  this._idfCache = {}
 
  this.on('add', 'remove', 'update', (function () {
    this._idfCache = {}
  }).bind(this))
}
 
/**
 * Bind a handler to events being emitted by the index.
 *
 * The handler can be bound to many events at the same time.
 *
 * @param {String} [eventName] The name(s) of events to bind the function to.
 * @param {Function} handler The serialised set to load.
 * @memberOf Index
 */
lunr.Index.prototype.on = function () {
  var args = Array.prototype.slice.call(arguments)
  return this.eventEmitter.addListener.apply(this.eventEmitter, args)
}
 
/**
 * Removes a handler from an event being emitted by the index.
 *
 * @param {String} eventName The name of events to remove the function from.
 * @param {Function} handler The serialised set to load.
 * @memberOf Index
 */
lunr.Index.prototype.off = function (name, fn) {
  return this.eventEmitter.removeListener(name, fn)
}
 
/**
 * Loads a previously serialised index.
 *
 * Issues a warning if the index being imported was serialised
 * by a different version of lunr.
 *
 * @param {Object} serialisedData The serialised set to load.
 * @returns {lunr.Index}
 * @memberOf Index
 */
lunr.Index.load = function (serialisedData) {
  if (serialisedData.version !== lunr.version) {
    lunr.utils.warn('version mismatch: current ' + lunr.version + ' importing ' + serialisedData.version)
  }
 
  var idx = new this
 
  idx._fields = serialisedData.fields
  idx._ref = serialisedData.ref
 
  idx.documentStore = lunr.Store.load(serialisedData.documentStore)
  idx.tokenStore = lunr.TokenStore.load(serialisedData.tokenStore)
  idx.corpusTokens = lunr.SortedSet.load(serialisedData.corpusTokens)
  idx.pipeline = lunr.Pipeline.load(serialisedData.pipeline)
 
  return idx
}
 
/**
 * Adds a field to the list of fields that will be searchable within documents
 * in the index.
 *
 * An optional boost param can be passed to affect how much tokens in this field
 * rank in search results, by default the boost value is 1.
 *
 * Fields should be added before any documents are added to the index, fields
 * that are added after documents are added to the index will only apply to new
 * documents added to the index.
 *
 * @param {String} fieldName The name of the field within the document that
 * should be indexed
 * @param {Number} boost An optional boost that can be applied to terms in this
 * field.
 * @returns {lunr.Index}
 * @memberOf Index
 */
lunr.Index.prototype.field = function (fieldName, opts) {
  var opts = opts || {},
      field = { name: fieldName, boost: opts.boost || 1 }
 
  this._fields.push(field)
  return this
}
 
/**
 * Sets the property used to uniquely identify documents added to the index,
 * by default this property is 'id'.
 *
 * This should only be changed before adding documents to the index, changing
 * the ref property without resetting the index can lead to unexpected results.
 *
 * @param {String} refName The property to use to uniquely identify the
 * documents in the index.
 * @param {Boolean} emitEvent Whether to emit add events, defaults to true
 * @returns {lunr.Index}
 * @memberOf Index
 */
lunr.Index.prototype.ref = function (refName) {
  this._ref = refName
  return this
}
 
/**
 * Add a document to the index.
 *
 * This is the way new documents enter the index, this function will run the
 * fields from the document through the index's pipeline and then add it to
 * the index, it will then show up in search results.
 *
 * An 'add' event is emitted with the document that has been added and the index
 * the document has been added to. This event can be silenced by passing false
 * as the second argument to add.
 *
 * @param {Object} doc The document to add to the index.
 * @param {Boolean} emitEvent Whether or not to emit events, default true.
 * @memberOf Index
 */
lunr.Index.prototype.add = function (doc, emitEvent) {
  var docTokens = {},
      allDocumentTokens = new lunr.SortedSet,
      docRef = doc[this._ref],
      emitEvent = emitEvent === undefined ? true : emitEvent
 
  this._fields.forEach(function (field) {
    var fieldTokens = this.pipeline.run(lunr.tokenizer(doc[field.name]))
 
    docTokens[field.name] = fieldTokens
    lunr.SortedSet.prototype.add.apply(allDocumentTokens, fieldTokens)
  }, this)
 
  this.documentStore.set(docRef, allDocumentTokens)
  lunr.SortedSet.prototype.add.apply(this.corpusTokens, allDocumentTokens.toArray())
 
  for (var i = 0; i < allDocumentTokens.length; i++) {
    var token = allDocumentTokens.elements[i]
    var tf = this._fields.reduce(function (memo, field) {
      var fieldLength = docTokens[field.name].length
 
      if (!fieldLength) return memo
 
      var tokenCount = docTokens[field.name].filter(function (t) { return t === token }).length
 
      return memo + (tokenCount / fieldLength * field.boost)
    }, 0)
 
    this.tokenStore.add(token, { ref: docRef, tf: tf })
  };
 
  if (emitEvent) this.eventEmitter.emit('add', doc, this)
}
 
/**
 * Removes a document from the index.
 *
 * To make sure documents no longer show up in search results they can be
 * removed from the index using this method.
 *
 * The document passed only needs to have the same ref property value as the
 * document that was added to the index, they could be completely different
 * objects.
 *
 * A 'remove' event is emitted with the document that has been removed and the index
 * the document has been removed from. This event can be silenced by passing false
 * as the second argument to remove.
 *
 * @param {Object} doc The document to remove from the index.
 * @param {Boolean} emitEvent Whether to emit remove events, defaults to true
 * @memberOf Index
 */
lunr.Index.prototype.remove = function (doc, emitEvent) {
  var docRef = doc[this._ref],
      emitEvent = emitEvent === undefined ? true : emitEvent
 
  if (!this.documentStore.has(docRef)) return
 
  var docTokens = this.documentStore.get(docRef)
 
  this.documentStore.remove(docRef)
 
  docTokens.forEach(function (token) {
    this.tokenStore.remove(token, docRef)
  }, this)
 
  if (emitEvent) this.eventEmitter.emit('remove', doc, this)
}
 
/**
 * Updates a document in the index.
 *
 * When a document contained within the index gets updated, fields changed,
 * added or removed, to make sure it correctly matched against search queries,
 * it should be updated in the index.
 *
 * This method is just a wrapper around `remove` and `add`
 *
 * An 'update' event is emitted with the document that has been updated and the index.
 * This event can be silenced by passing false as the second argument to update. Only
 * an update event will be fired, the 'add' and 'remove' events of the underlying calls
 * are silenced.
 *
 * @param {Object} doc The document to update in the index.
 * @param {Boolean} emitEvent Whether to emit update events, defaults to true
 * @see Index.prototype.remove
 * @see Index.prototype.add
 * @memberOf Index
 */
lunr.Index.prototype.update = function (doc, emitEvent) {
  var emitEvent = emitEvent === undefined ? true : emitEvent
 
  this.remove(doc, false)
  this.add(doc, false)
 
  if (emitEvent) this.eventEmitter.emit('update', doc, this)
}
 
/**
 * Calculates the inverse document frequency for a token within the index.
 *
 * @param {String} token The token to calculate the idf of.
 * @see Index.prototype.idf
 * @private
 * @memberOf Index
 */
lunr.Index.prototype.idf = function (term) {
  var cacheKey = "@" + term
  if (Object.prototype.hasOwnProperty.call(this._idfCache, cacheKey)) return this._idfCache[cacheKey]
 
  var documentFrequency = this.tokenStore.count(term),
      idf = 1
 
  if (documentFrequency > 0) {
    idf = 1 + Math.log(this.tokenStore.length / documentFrequency)
  }
 
  return this._idfCache[cacheKey] = idf
}
 
/**
 * Searches the index using the passed query.
 *
 * Queries should be a string, multiple words are allowed and will lead to an
 * AND based query, e.g. `idx.search('foo bar')` will run a search for
 * documents containing both 'foo' and 'bar'.
 *
 * All query tokens are passed through the same pipeline that document tokens
 * are passed through, so any language processing involved will be run on every
 * query term.
 *
 * Each query term is expanded, so that the term 'he' might be expanded to
 * 'hello' and 'help' if those terms were already included in the index.
 *
 * Matching documents are returned as an array of objects, each object contains
 * the matching document ref, as set for this index, and the similarity score
 * for this document against the query.
 *
 * @param {String} query The query to search the index with.
 * @returns {Object}
 * @see Index.prototype.idf
 * @see Index.prototype.documentVector
 * @memberOf Index
 */
lunr.Index.prototype.search = function (query) {
  var queryTokens = this.pipeline.run(lunr.tokenizer(query)),
      queryVector = new lunr.Vector,
      documentSets = [],
      fieldBoosts = this._fields.reduce(function (memo, f) { return memo + f.boost }, 0)
 
  var hasSomeToken = queryTokens.some(function (token) {
    return this.tokenStore.has(token)
  }, this)
 
  if (!hasSomeToken) return []
 
  queryTokens
    .forEach(function (token, i, tokens) {
      var tf = 1 / tokens.length * this._fields.length * fieldBoosts,
          self = this
 
      var set = this.tokenStore.expand(token).reduce(function (memo, key) {
        var pos = self.corpusTokens.indexOf(key),
            idf = self.idf(key),
            similarityBoost = 1,
            set = new lunr.SortedSet
 
        // if the expanded key is not an exact match to the token then
        // penalise the score for this key by how different the key is
        // to the token.
        if (key !== token) {
          var diff = Math.max(3, key.length - token.length)
          similarityBoost = 1 / Math.log(diff)
        }
 
        // calculate the query tf-idf score for this token
        // applying an similarityBoost to ensure exact matches
        // these rank higher than expanded terms
        if (pos > -1) queryVector.insert(pos, tf * idf * similarityBoost)
 
        // add all the documents that have this key into a set
        Object.keys(self.tokenStore.get(key)).forEach(function (ref) { set.add(ref) })
 
        return memo.union(set)
      }, new lunr.SortedSet)
 
      documentSets.push(set)
    }, this)
 
  var documentSet = documentSets.reduce(function (memo, set) {
    return memo.intersect(set)
  })
 
  return documentSet
    .map(function (ref) {
      return { ref: ref, score: queryVector.similarity(this.documentVector(ref)) }
    }, this)
    .sort(function (a, b) {
      return b.score - a.score
    })
}
 
/**
 * Generates a vector containing all the tokens in the document matching the
 * passed documentRef.
 *
 * The vector contains the tf-idf score for each token contained in the
 * document with the passed documentRef.  The vector will contain an element
 * for every token in the indexes corpus, if the document does not contain that
 * token the element will be 0.
 *
 * @param {Object} documentRef The ref to find the document with.
 * @returns {lunr.Vector}
 * @private
 * @memberOf Index
 */
lunr.Index.prototype.documentVector = function (documentRef) {
  var documentTokens = this.documentStore.get(documentRef),
      documentTokensLength = documentTokens.length,
      documentVector = new lunr.Vector
 
  for (var i = 0; i < documentTokensLength; i++) {
    var token = documentTokens.elements[i],
        tf = this.tokenStore.get(token)[documentRef].tf,
        idf = this.idf(token)
 
    documentVector.insert(this.corpusTokens.indexOf(token), tf * idf)
  };
 
  return documentVector
}
 
/**
 * Returns a representation of the index ready for serialisation.
 *
 * @returns {Object}
 * @memberOf Index
 */
lunr.Index.prototype.toJSON = function () {
  return {
    version: lunr.version,
    fields: this._fields,
    ref: this._ref,
    documentStore: this.documentStore.toJSON(),
    tokenStore: this.tokenStore.toJSON(),
    corpusTokens: this.corpusTokens.toJSON(),
    pipeline: this.pipeline.toJSON()
  }
}
 
/**
 * Applies a plugin to the current index.
 *
 * A plugin is a function that is called with the index as its context.
 * Plugins can be used to customise or extend the behaviour the index
 * in some way. A plugin is just a function, that encapsulated the custom
 * behaviour that should be applied to the index.
 *
 * The plugin function will be called with the index as its argument, additional
 * arguments can also be passed when calling use. The function will be called
 * with the index as its context.
 *
 * Example:
 *
 *     var myPlugin = function (idx, arg1, arg2) {
 *       // `this` is the index to be extended
 *       // apply any extensions etc here.
 *     }
 *
 *     var idx = lunr(function () {
 *       this.use(myPlugin, 'arg1', 'arg2')
 *     })
 *
 * @param {Function} plugin The plugin to apply.
 * @memberOf Index
 */
lunr.Index.prototype.use = function (plugin) {
  var args = Array.prototype.slice.call(arguments, 1)
  args.unshift(this)
  plugin.apply(this, args)
}
/*!
 * lunr.Store
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.Store is a simple key-value store used for storing sets of tokens for
 * documents stored in index.
 *
 * @constructor
 * @module
 */
lunr.Store = function () {
  this.store = {}
  this.length = 0
}
 
/**
 * Loads a previously serialised store
 *
 * @param {Object} serialisedData The serialised store to load.
 * @returns {lunr.Store}
 * @memberOf Store
 */
lunr.Store.load = function (serialisedData) {
  var store = new this
 
  store.length = serialisedData.length
  store.store = Object.keys(serialisedData.store).reduce(function (memo, key) {
    memo[key] = lunr.SortedSet.load(serialisedData.store[key])
    return memo
  }, {})
 
  return store
}
 
/**
 * Stores the given tokens in the store against the given id.
 *
 * @param {Object} id The key used to store the tokens against.
 * @param {Object} tokens The tokens to store against the key.
 * @memberOf Store
 */
lunr.Store.prototype.set = function (id, tokens) {
  if (!this.has(id)) this.length++
  this.store[id] = tokens
}
 
/**
 * Retrieves the tokens from the store for a given key.
 *
 * @param {Object} id The key to lookup and retrieve from the store.
 * @returns {Object}
 * @memberOf Store
 */
lunr.Store.prototype.get = function (id) {
  return this.store[id]
}
 
/**
 * Checks whether the store contains a key.
 *
 * @param {Object} id The id to look up in the store.
 * @returns {Boolean}
 * @memberOf Store
 */
lunr.Store.prototype.has = function (id) {
  return id in this.store
}
 
/**
 * Removes the value for a key in the store.
 *
 * @param {Object} id The id to remove from the store.
 * @memberOf Store
 */
lunr.Store.prototype.remove = function (id) {
  if (!this.has(id)) return
 
  delete this.store[id]
  this.length--
}
 
/**
 * Returns a representation of the store ready for serialisation.
 *
 * @returns {Object}
 * @memberOf Store
 */
lunr.Store.prototype.toJSON = function () {
  return {
    store: this.store,
    length: this.length
  }
}
 
/*!
 * lunr.stemmer
 * Copyright (C) 2015 Oliver Nightingale
 * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt
 */
 
/**
 * lunr.stemmer is an english language stemmer, this is a JavaScript
 * implementation of the PorterStemmer taken from http://tartarus.org/~martin
 *
 * @module
 * @param {String} str The string to stem
 * @returns {String}
 * @see lunr.Pipeline
 */
lunr.stemmer = (function(){
  var step2list = {
      "ational" : "ate",
      "tional" : "tion",
      "enci" : "ence",
      "anci" : "ance",
      "izer" : "ize",
      "bli" : "ble",
      "alli" : "al",
      "entli" : "ent",
      "eli" : "e",
      "ousli" : "ous",
      "ization" : "ize",
      "ation" : "ate",
      "ator" : "ate",
      "alism" : "al",
      "iveness" : "ive",
      "fulness" : "ful",
      "ousness" : "ous",
      "aliti" : "al",
      "iviti" : "ive",
      "biliti" : "ble",
      "logi" : "log"
    },
 
    step3list = {
      "icate" : "ic",
      "ative" : "",
      "alize" : "al",
      "iciti" : "ic",
      "ical" : "ic",
      "ful" : "",
      "ness" : ""
    },
 
    c = "[^aeiou]",          // consonant
    v = "[aeiouy]",          // vowel
    C = c + "[^aeiouy]*",    // consonant sequence
    V = v + "[aeiou]*",      // vowel sequence
 
    mgr0 = "^(" + C + ")?" + V + C,               // [C]VC... is m>0
    meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$",  // [C]VC[V] is m=1
    mgr1 = "^(" + C + ")?" + V + C + V + C,       // [C]VCVC... is m>1
    s_v = "^(" + C + ")?" + v;                   // vowel in stem
 
  var re_mgr0 = new RegExp(mgr0);
  var re_mgr1 = new RegExp(mgr1);
  var re_meq1 = new RegExp(meq1);
  var re_s_v = new RegExp(s_v);
 
  var re_1a = /^(.+?)(ss|i)es$/;
  var re2_1a = /^(.+?)([^s])s$/;
  var re_1b = /^(.+?)eed$/;
  var re2_1b = /^(.+?)(ed|ing)$/;
  var re_1b_2 = /.$/;
  var re2_1b_2 = /(at|bl|iz)$/;
  var re3_1b_2 = new RegExp("([^aeiouylsz])\\1$");
  var re4_1b_2 = new RegExp("^" + C + v + "[^aeiouwxy]$");
 
  var re_1c = /^(.+?[^aeiou])y$/;
  var re_2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
 
  var re_3 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
 
  var re_4 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
  var re2_4 = /^(.+?)(s|t)(ion)$/;
 
  var re_5 = /^(.+?)e$/;
  var re_5_1 = /ll$/;
  var re3_5 = new RegExp("^" + C + v + "[^aeiouwxy]$");
 
  var porterStemmer = function porterStemmer(w) {
    var   stem,
      suffix,
      firstch,
      re,
      re2,
      re3,
      re4;
 
    if (w.length < 3) { return w; }
 
    firstch = w.substr(0,1);
    if (firstch == "y") {
      w = firstch.toUpperCase() + w.substr(1);
    }
 
    // Step 1a
    re = re_1a
    re2 = re2_1a;
 
    if (re.test(w)) { w = w.replace(re,"$1$2"); }
    else if (re2.test(w)) { w = w.replace(re2,"$1$2"); }
 
    // Step 1b
    re = re_1b;
    re2 = re2_1b;
    if (re.test(w)) {
      var fp = re.exec(w);
      re = re_mgr0;
      if (re.test(fp[1])) {
        re = re_1b_2;
        w = w.replace(re,"");
      }
    } else if (re2.test(w)) {
      var fp = re2.exec(w);
      stem = fp[1];
      re2 = re_s_v;
      if (re2.test(stem)) {
        w = stem;
        re2 = re2_1b_2;
        re3 = re3_1b_2;
        re4 = re4_1b_2;
        if (re2.test(w)) {  w = w + "e"; }
        else if (re3.test(w)) { re = re_1b_2; w = w.replace(re,""); }
        else if (re4.test(w)) { w = w + "e"; }
      }
    }
 
    // Step 1c - replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say)
    re = re_1c;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      w = stem + "i";
    }
 
    // Step 2
    re = re_2;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      suffix = fp[2];
      re = re_mgr0;
      if (re.test(stem)) {
        w = stem + step2list[suffix];
      }
    }
 
    // Step 3
    re = re_3;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      suffix = fp[2];
      re = re_mgr0;
      if (re.test(stem)) {
        w = stem + step3list[suffix];
      }
    }
 
    // Step 4
    re = re_4;
    re2 = re2_4;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      re = re_mgr1;
      if (re.test(stem)) {
        w = stem;
      }
    } else if (re2.test(w)) {
      var fp = re2.exec(w);
      stem = fp[1] + fp[2];
      re2 = re_mgr1;
      if (re2.test(stem)) {
        w = stem;
      }
    }
 
    // Step 5
    re = re_5;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      re = re_mgr1;
      re2 = re_meq1;
      re3 = re3_5;
      if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) {
        w = stem;
      }
    }
 
    re = re_5_1;
    re2 = re_mgr1;
    if (re.test(w) && re2.test(w)) {
      re = re_1b_2;
      w = w.replace(re,"");
    }
 
    // and turn initial Y back to y
 
    if (firstch == "y") {
      w = firstch.toLowerCase() + w.substr(1);
    }
 
    return w;
  };
 
  return porterStemmer;
})();
 
lunr.Pipeline.registerFunction(lunr.stemmer, 'stemmer')
/*!
 * lunr.stopWordFilter
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.stopWordFilter is an English language stop word list filter, any words
 * contained in the list will not be passed through the filter.
 *
 * This is intended to be used in the Pipeline. If the token does not pass the
 * filter then undefined will be returned.
 *
 * @module
 * @param {String} token The token to pass through the filter
 * @returns {String}
 * @see lunr.Pipeline
 */
lunr.stopWordFilter = function (token) {
  if (lunr.stopWordFilter.stopWords.indexOf(token) === -1) return token
}
 
lunr.stopWordFilter.stopWords = new lunr.SortedSet
lunr.stopWordFilter.stopWords.length = 119
lunr.stopWordFilter.stopWords.elements = [
  "",
  "a",
  "able",
  "about",
  "across",
  "after",
  "all",
  "almost",
  "also",
  "am",
  "among",
  "an",
  "and",
  "any",
  "are",
  "as",
  "at",
  "be",
  "because",
  "been",
  "but",
  "by",
  "can",
  "cannot",
  "could",
  "dear",
  "did",
  "do",
  "does",
  "either",
  "else",
  "ever",
  "every",
  "for",
  "from",
  "get",
  "got",
  "had",
  "has",
  "have",
  "he",
  "her",
  "hers",
  "him",
  "his",
  "how",
  "however",
  "i",
  "if",
  "in",
  "into",
  "is",
  "it",
  "its",
  "just",
  "least",
  "let",
  "like",
  "likely",
  "may",
  "me",
  "might",
  "most",
  "must",
  "my",
  "neither",
  "no",
  "nor",
  "not",
  "of",
  "off",
  "often",
  "on",
  "only",
  "or",
  "other",
  "our",
  "own",
  "rather",
  "said",
  "say",
  "says",
  "she",
  "should",
  "since",
  "so",
  "some",
  "than",
  "that",
  "the",
  "their",
  "them",
  "then",
  "there",
  "these",
  "they",
  "this",
  "tis",
  "to",
  "too",
  "twas",
  "us",
  "wants",
  "was",
  "we",
  "were",
  "what",
  "when",
  "where",
  "which",
  "while",
  "who",
  "whom",
  "why",
  "will",
  "with",
  "would",
  "yet",
  "you",
  "your"
]
 
lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'stopWordFilter')
/*!
 * lunr.trimmer
 * Copyright (C) 2015 Oliver Nightingale
 */
 
/**
 * lunr.trimmer is a pipeline function for trimming non word
 * characters from the begining and end of tokens before they
 * enter the index.
 *
 * This implementation may not work correctly for non latin
 * characters and should either be removed or adapted for use
 * with languages with non-latin characters.
 *
 * @module
 * @param {String} token The token to pass through the filter
 * @returns {String}
 * @see lunr.Pipeline
 */
lunr.trimmer = function (token) {
  return token
    .replace(/^\W+/, '')
    .replace(/\W+$/, '')
}
 
lunr.Pipeline.registerFunction(lunr.trimmer, 'trimmer')
/*!
 * lunr.stemmer
 * Copyright (C) 2015 Oliver Nightingale
 * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt
 */
 
/**
 * lunr.TokenStore is used for efficient storing and lookup of the reverse
 * index of token to document ref.
 *
 * @constructor
 */
lunr.TokenStore = function () {
  this.root = { docs: {} }
  this.length = 0
}
 
/**
 * Loads a previously serialised token store
 *
 * @param {Object} serialisedData The serialised token store to load.
 * @returns {lunr.TokenStore}
 * @memberOf TokenStore
 */
lunr.TokenStore.load = function (serialisedData) {
  var store = new this
 
  store.root = serialisedData.root
  store.length = serialisedData.length
 
  return store
}
 
/**
 * Adds a new token doc pair to the store.
 *
 * By default this function starts at the root of the current store, however
 * it can start at any node of any token store if required.
 *
 * @param {String} token The token to store the doc under
 * @param {Object} doc The doc to store against the token
 * @param {Object} root An optional node at which to start looking for the
 * correct place to enter the doc, by default the root of this lunr.TokenStore
 * is used.
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.add = function (token, doc, root) {
  var root = root || this.root,
      key = token[0],
      rest = token.slice(1)
 
  if (!(key in root)) root[key] = {docs: {}}
 
  if (rest.length === 0) {
    root[key].docs[doc.ref] = doc
    this.length += 1
    return
  } else {
    return this.add(rest, doc, root[key])
  }
}
 
/**
 * Checks whether this key is contained within this lunr.TokenStore.
 *
 * By default this function starts at the root of the current store, however
 * it can start at any node of any token store if required.
 *
 * @param {String} token The token to check for
 * @param {Object} root An optional node at which to start
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.has = function (token) {
  if (!token) return false
 
  var node = this.root
 
  for (var i = 0; i < token.length; i++) {
    if (!node[token[i]]) return false
 
    node = node[token[i]]
  }
 
  return true
}
 
/**
 * Retrieve a node from the token store for a given token.
 *
 * By default this function starts at the root of the current store, however
 * it can start at any node of any token store if required.
 *
 * @param {String} token The token to get the node for.
 * @param {Object} root An optional node at which to start.
 * @returns {Object}
 * @see TokenStore.prototype.get
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.getNode = function (token) {
  if (!token) return {}
 
  var node = this.root
 
  for (var i = 0; i < token.length; i++) {
    if (!node[token[i]]) return {}
 
    node = node[token[i]]
  }
 
  return node
}
 
/**
 * Retrieve the documents for a node for the given token.
 *
 * By default this function starts at the root of the current store, however
 * it can start at any node of any token store if required.
 *
 * @param {String} token The token to get the documents for.
 * @param {Object} root An optional node at which to start.
 * @returns {Object}
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.get = function (token, root) {
  return this.getNode(token, root).docs || {}
}
 
lunr.TokenStore.prototype.count = function (token, root) {
  return Object.keys(this.get(token, root)).length
}
 
/**
 * Remove the document identified by ref from the token in the store.
 *
 * By default this function starts at the root of the current store, however
 * it can start at any node of any token store if required.
 *
 * @param {String} token The token to get the documents for.
 * @param {String} ref The ref of the document to remove from this token.
 * @param {Object} root An optional node at which to start.
 * @returns {Object}
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.remove = function (token, ref) {
  if (!token) return
  var node = this.root
 
  for (var i = 0; i < token.length; i++) {
    if (!(token[i] in node)) return
    node = node[token[i]]
  }
 
  delete node.docs[ref]
}
 
/**
 * Find all the possible suffixes of the passed token using tokens
 * currently in the store.
 *
 * @param {String} token The token to expand.
 * @returns {Array}
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.expand = function (token, memo) {
  var root = this.getNode(token),
      docs = root.docs || {},
      memo = memo || []
 
  if (Object.keys(docs).length) memo.push(token)
 
  Object.keys(root)
    .forEach(function (key) {
      if (key === 'docs') return
 
      memo.concat(this.expand(token + key, memo))
    }, this)
 
  return memo
}
 
/**
 * Returns a representation of the token store ready for serialisation.
 *
 * @returns {Object}
 * @memberOf TokenStore
 */
lunr.TokenStore.prototype.toJSON = function () {
  return {
    root: this.root,
    length: this.length
  }
}
 
 
  /**
   * export the module via AMD, CommonJS or as a browser global
   * Export code from https://github.com/umdjs/umd/blob/master/returnExports.js
   */
  ;(function (root, factory) {
    Iif (typeof define === 'function' && define.amd) {
      // AMD. Register as an anonymous module.
      define(factory)
    } else Eif (typeof exports === 'object') {
      /**
       * Node. Does not work with strict CommonJS, but
       * only CommonJS-like enviroments that support module.exports,
       * like Node.
       */
      module.exports = factory()
    } else {
      // Browser globals (root is window)
      root.lunr = factory()
    }
  }(this, function () {
    /**
     * Just return a value to define the module export.
     * This example returns an object, but the module
     * can return a function as the exported value.
     */
    return lunr
  }))
})()
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/

Statements: 8.77% (42 / 479)      Branches: 1.64% (5 / 305)      Functions: 6.38% (3 / 47)      Lines: 9.23% (41 / 444)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/minimatch/
File Statements Branches Functions Lines
minimatch.js 8.77% (42 / 479) 1.64% (5 / 305) 6.38% (3 / 47) 9.23% (41 / 444)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/minimatch.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/minimatch.js

Statements: 8.77% (42 / 479)      Branches: 1.64% (5 / 305)      Functions: 6.38% (3 / 47)      Lines: 9.23% (41 / 444)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 10751   1     1                                                     1   1         1                                         1 1 14 14         1   1 1             1                         1                               1           1                                   1                                                                           1   1 1                                                                                                             1 1                                                         1       1   1           1                                                                                                                                                                                                           1                                                                                                                                                                                                                     1 1 1                                                 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1       1 1                                                                                 1                       1 1                                                                                                                     1                                                                                                                                                                                                                                                                                                                                 1         1                    
;(function (require, exports, module, platform) {
 
Eif (module) module.exports = minimatch
else exports.minimatch = minimatch
 
Iif (!require) {
  require = function (id) {
    switch (id) {
      case "sigmund": return function sigmund (obj) {
        return JSON.stringify(obj)
      }
      case "path": return { basename: function (f) {
        f = f.split(/[\/\\]/)
        var e = f.pop()
        if (!e) e = f.pop()
        return e
      }}
      case "lru-cache": return function LRUCache () {
        // not quite an LRU, but still space-limited.
        var cache = {}
        var cnt = 0
        this.set = function (k, v) {
          cnt ++
          if (cnt >= 100) cache = {}
          cache[k] = v
        }
        this.get = function (k) { return cache[k] }
      }
    }
  }
}
 
minimatch.Minimatch = Minimatch
 
var LRU = require("lru-cache")
  , cache = minimatch.cache = new LRU({max: 100})
  , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
  , sigmund = require("sigmund")
 
var path = require("path")
  // any single thing other than /
  // don't need to escape / when using new RegExp()
  , qmark = "[^/]"
 
  // * => any number of characters
  , star = qmark + "*?"
 
  // ** when dots are allowed.  Anything goes, except .. and .
  // not (^ or / followed by one or two dots followed by $ or /),
  // followed by anything, any number of times.
  , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?"
 
  // not a ^ or / followed by a dot,
  // followed by anything, any number of times.
  , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?"
 
  // characters that need to be escaped in RegExp.
  , reSpecials = charSet("().*{}+?[]^$\\!")
 
// "abc" -> { a:true, b:true, c:true }
function charSet (s) {
  return s.split("").reduce(function (set, c) {
    set[c] = true
    return set
  }, {})
}
 
// normalizes slashes.
var slashSplit = /\/+/
 
minimatch.filter = filter
function filter (pattern, options) {
  options = options || {}
  return function (p, i, list) {
    return minimatch(p, pattern, options)
  }
}
 
function ext (a, b) {
  a = a || {}
  b = b || {}
  var t = {}
  Object.keys(b).forEach(function (k) {
    t[k] = b[k]
  })
  Object.keys(a).forEach(function (k) {
    t[k] = a[k]
  })
  return t
}
 
minimatch.defaults = function (def) {
  if (!def || !Object.keys(def).length) return minimatch
 
  var orig = minimatch
 
  var m = function minimatch (p, pattern, options) {
    return orig.minimatch(p, pattern, ext(def, options))
  }
 
  m.Minimatch = function Minimatch (pattern, options) {
    return new orig.Minimatch(pattern, ext(def, options))
  }
 
  return m
}
 
Minimatch.defaults = function (def) {
  if (!def || !Object.keys(def).length) return Minimatch
  return minimatch.defaults(def).Minimatch
}
 
 
function minimatch (p, pattern, options) {
  if (typeof pattern !== "string") {
    throw new TypeError("glob pattern string required")
  }
 
  if (!options) options = {}
 
  // shortcut: comments match nothing.
  if (!options.nocomment && pattern.charAt(0) === "#") {
    return false
  }
 
  // "" only matches ""
  if (pattern.trim() === "") return p === ""
 
  return new Minimatch(pattern, options).match(p)
}
 
function Minimatch (pattern, options) {
  if (!(this instanceof Minimatch)) {
    return new Minimatch(pattern, options, cache)
  }
 
  if (typeof pattern !== "string") {
    throw new TypeError("glob pattern string required")
  }
 
  if (!options) options = {}
  pattern = pattern.trim()
 
  // windows: need to use /, not \
  // On other platforms, \ is a valid (albeit bad) filename char.
  if (platform === "win32") {
    pattern = pattern.split("\\").join("/")
  }
 
  // lru storage.
  // these things aren't particularly big, but walking down the string
  // and turning it into a regexp can get pretty costly.
  var cacheKey = pattern + "\n" + sigmund(options)
  var cached = minimatch.cache.get(cacheKey)
  if (cached) return cached
  minimatch.cache.set(cacheKey, this)
 
  this.options = options
  this.set = []
  this.pattern = pattern
  this.regexp = null
  this.negate = false
  this.comment = false
  this.empty = false
 
  // make the set of regexps etc.
  this.make()
}
 
Minimatch.prototype.debug = function() {}
 
Minimatch.prototype.make = make
function make () {
  // don't do it more than once.
  if (this._made) return
 
  var pattern = this.pattern
  var options = this.options
 
  // empty patterns and comments match nothing.
  if (!options.nocomment && pattern.charAt(0) === "#") {
    this.comment = true
    return
  }
  if (!pattern) {
    this.empty = true
    return
  }
 
  // step 1: figure out negation, etc.
  this.parseNegate()
 
  // step 2: expand braces
  var set = this.globSet = this.braceExpand()
 
  if (options.debug) this.debug = console.error
 
  this.debug(this.pattern, set)
 
  // step 3: now we have a set, so turn each one into a series of path-portion
  // matching patterns.
  // These will be regexps, except in the case of "**", which is
  // set to the GLOBSTAR object for globstar behavior,
  // and will not contain any / characters
  set = this.globParts = set.map(function (s) {
    return s.split(slashSplit)
  })
 
  this.debug(this.pattern, set)
 
  // glob --> regexps
  set = set.map(function (s, si, set) {
    return s.map(this.parse, this)
  }, this)
 
  this.debug(this.pattern, set)
 
  // filter out everything that didn't compile properly.
  set = set.filter(function (s) {
    return -1 === s.indexOf(false)
  })
 
  this.debug(this.pattern, set)
 
  this.set = set
}
 
Minimatch.prototype.parseNegate = parseNegate
function parseNegate () {
  var pattern = this.pattern
    , negate = false
    , options = this.options
    , negateOffset = 0
 
  if (options.nonegate) return
 
  for ( var i = 0, l = pattern.length
      ; i < l && pattern.charAt(i) === "!"
      ; i ++) {
    negate = !negate
    negateOffset ++
  }
 
  if (negateOffset) this.pattern = pattern.substr(negateOffset)
  this.negate = negate
}
 
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
  return new Minimatch(pattern, options).braceExpand()
}
 
Minimatch.prototype.braceExpand = braceExpand
 
function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
 
function braceExpand (pattern, options) {
  options = options || this.options
  pattern = typeof pattern === "undefined"
    ? this.pattern : pattern
 
  if (typeof pattern === "undefined") {
    throw new Error("undefined pattern")
  }
 
  if (options.nobrace ||
      !pattern.match(/\{.*\}/)) {
    // shortcut. no need to expand.
    return [pattern]
  }
 
  var escaping = false
 
  // examples and comments refer to this crazy pattern:
  // a{b,c{d,e},{f,g}h}x{y,z}
  // expected:
  // abxy
  // abxz
  // acdxy
  // acdxz
  // acexy
  // acexz
  // afhxy
  // afhxz
  // aghxy
  // aghxz
 
  // everything before the first \{ is just a prefix.
  // So, we pluck that off, and work with the rest,
  // and then prepend it to everything we find.
  if (pattern.charAt(0) !== "{") {
    this.debug(pattern)
    var prefix = null
    for (var i = 0, l = pattern.length; i < l; i ++) {
      var c = pattern.charAt(i)
      this.debug(i, c)
      if (c === "\\") {
        escaping = !escaping
      } else if (c === "{" && !escaping) {
        prefix = pattern.substr(0, i)
        break
      }
    }
 
    // actually no sets, all { were escaped.
    if (prefix === null) {
      this.debug("no sets")
      return [pattern]
    }
 
   var tail = braceExpand.call(this, pattern.substr(i), options)
    return tail.map(function (t) {
      return prefix + t
    })
  }
 
  // now we have something like:
  // {b,c{d,e},{f,g}h}x{y,z}
  // walk through the set, expanding each part, until
  // the set ends.  then, we'll expand the suffix.
  // If the set only has a single member, then'll put the {} back
 
  // first, handle numeric sets, since they're easier
  var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/)
  if (numset) {
    this.debug("numset", numset[1], numset[2])
    var suf = braceExpand.call(this, pattern.substr(numset[0].length), options)
      , start = +numset[1]
      , needPadding = numset[1][0] === '0'
      , startWidth = numset[1].length
      , padded
      , end = +numset[2]
      , inc = start > end ? -1 : 1
      , set = []
 
    for (var i = start; i != (end + inc); i += inc) {
      padded = needPadding ? pad(i, startWidth) : i + ''
      // append all the suffixes
      for (var ii = 0, ll = suf.length; ii < ll; ii ++) {
        set.push(padded + suf[ii])
      }
    }
    return set
  }
 
  // ok, walk through the set
  // We hope, somewhat optimistically, that there
  // will be a } at the end.
  // If the closing brace isn't found, then the pattern is
  // interpreted as braceExpand("\\" + pattern) so that
  // the leading \{ will be interpreted literally.
  var i = 1 // skip the \{
    , depth = 1
    , set = []
    , member = ""
    , sawEnd = false
    , escaping = false
 
  function addMember () {
    set.push(member)
    member = ""
  }
 
  this.debug("Entering for")
  FOR: for (i = 1, l = pattern.length; i < l; i ++) {
    var c = pattern.charAt(i)
    this.debug("", i, c)
 
    if (escaping) {
      escaping = false
      member += "\\" + c
    } else {
      switch (c) {
        case "\\":
          escaping = true
          continue
 
        case "{":
          depth ++
          member += "{"
          continue
 
        case "}":
          depth --
          // if this closes the actual set, then we're done
          if (depth === 0) {
            addMember()
            // pluck off the close-brace
            i ++
            break FOR
          } else {
            member += c
            continue
          }
 
        case ",":
          if (depth === 1) {
            addMember()
          } else {
            member += c
          }
          continue
 
        default:
          member += c
          continue
      } // switch
    } // else
  } // for
 
  // now we've either finished the set, and the suffix is
  // pattern.substr(i), or we have *not* closed the set,
  // and need to escape the leading brace
  if (depth !== 0) {
    this.debug("didn't close", pattern)
    return braceExpand.call(this, "\\" + pattern, options)
  }
 
  // x{y,z} -> ["xy", "xz"]
  this.debug("set", set)
  this.debug("suffix", pattern.substr(i))
  var suf = braceExpand.call(this, pattern.substr(i), options)
  // ["b", "c{d,e}","{f,g}h"] ->
  //   [["b"], ["cd", "ce"], ["fh", "gh"]]
  var addBraces = set.length === 1
  this.debug("set pre-expanded", set)
  set = set.map(function (p) {
    return braceExpand.call(this, p, options)
  }, this)
  this.debug("set expanded", set)
 
 
  // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
  //   ["b", "cd", "ce", "fh", "gh"]
  set = set.reduce(function (l, r) {
    return l.concat(r)
  })
 
  if (addBraces) {
    set = set.map(function (s) {
      return "{" + s + "}"
    })
  }
 
  // now attach the suffixes.
  var ret = []
  for (var i = 0, l = set.length; i < l; i ++) {
    for (var ii = 0, ll = suf.length; ii < ll; ii ++) {
      ret.push(set[i] + suf[ii])
    }
  }
  return ret
}
 
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion.  Otherwise, any series
// of * is equivalent to a single *.  Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse
var SUBPARSE = {}
function parse (pattern, isSub) {
  var options = this.options
 
  // shortcuts
  if (!options.noglobstar && pattern === "**") return GLOBSTAR
  if (pattern === "") return ""
 
  var re = ""
    , hasMagic = !!options.nocase
    , escaping = false
    // ? => one single character
    , patternListStack = []
    , plType
    , stateChar
    , inClass = false
    , reClassStart = -1
    , classStart = -1
    // . and .. never match anything that doesn't start with .,
    // even when options.dot is set.
    , patternStart = pattern.charAt(0) === "." ? "" // anything
      // not (start or / followed by . or .. followed by / or end)
      : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))"
      : "(?!\\.)"
    , self = this
 
  function clearStateChar () {
    if (stateChar) {
      // we had some state-tracking character
      // that wasn't consumed by this pass.
      switch (stateChar) {
        case "*":
          re += star
          hasMagic = true
          break
        case "?":
          re += qmark
          hasMagic = true
          break
        default:
          re += "\\"+stateChar
          break
      }
      self.debug('clearStateChar %j %j', stateChar, re)
      stateChar = false
    }
  }
 
  for ( var i = 0, len = pattern.length, c
      ; (i < len) && (c = pattern.charAt(i))
      ; i ++ ) {
 
    this.debug("%s\t%s %s %j", pattern, i, re, c)
 
    // skip over any that are escaped.
    if (escaping && reSpecials[c]) {
      re += "\\" + c
      escaping = false
      continue
    }
 
    SWITCH: switch (c) {
      case "/":
        // completely not allowed, even escaped.
        // Should already be path-split by now.
        return false
 
      case "\\":
        clearStateChar()
        escaping = true
        continue
 
      // the various stateChar values
      // for the "extglob" stuff.
      case "?":
      case "*":
      case "+":
      case "@":
      case "!":
        this.debug("%s\t%s %s %j <-- stateChar", pattern, i, re, c)
 
        // all of those are literals inside a class, except that
        // the glob [!a] means [^a] in regexp
        if (inClass) {
          this.debug('  in class')
          if (c === "!" && i === classStart + 1) c = "^"
          re += c
          continue
        }
 
        // if we already have a stateChar, then it means
        // that there was something like ** or +? in there.
        // Handle the stateChar, then proceed with this one.
        self.debug('call clearStateChar %j', stateChar)
        clearStateChar()
        stateChar = c
        // if extglob is disabled, then +(asdf|foo) isn't a thing.
        // just clear the statechar *now*, rather than even diving into
        // the patternList stuff.
        if (options.noext) clearStateChar()
        continue
 
      case "(":
        if (inClass) {
          re += "("
          continue
        }
 
        if (!stateChar) {
          re += "\\("
          continue
        }
 
        plType = stateChar
        patternListStack.push({ type: plType
                              , start: i - 1
                              , reStart: re.length })
        // negation is (?:(?!js)[^/]*)
        re += stateChar === "!" ? "(?:(?!" : "(?:"
        this.debug('plType %j %j', stateChar, re)
        stateChar = false
        continue
 
      case ")":
        if (inClass || !patternListStack.length) {
          re += "\\)"
          continue
        }
 
        clearStateChar()
        hasMagic = true
        re += ")"
        plType = patternListStack.pop().type
        // negation is (?:(?!js)[^/]*)
        // The others are (?:<pattern>)<type>
        switch (plType) {
          case "!":
            re += "[^/]*?)"
            break
          case "?":
          case "+":
          case "*": re += plType
          case "@": break // the default anyway
        }
        continue
 
      case "|":
        if (inClass || !patternListStack.length || escaping) {
          re += "\\|"
          escaping = false
          continue
        }
 
        clearStateChar()
        re += "|"
        continue
 
      // these are mostly the same in regexp and glob
      case "[":
        // swallow any state-tracking char before the [
        clearStateChar()
 
        if (inClass) {
          re += "\\" + c
          continue
        }
 
        inClass = true
        classStart = i
        reClassStart = re.length
        re += c
        continue
 
      case "]":
        //  a right bracket shall lose its special
        //  meaning and represent itself in
        //  a bracket expression if it occurs
        //  first in the list.  -- POSIX.2 2.8.3.2
        if (i === classStart + 1 || !inClass) {
          re += "\\" + c
          escaping = false
          continue
        }
 
        // finish up the class.
        hasMagic = true
        inClass = false
        re += c
        continue
 
      default:
        // swallow any state char that wasn't consumed
        clearStateChar()
 
        if (escaping) {
          // no need
          escaping = false
        } else if (reSpecials[c]
                   && !(c === "^" && inClass)) {
          re += "\\"
        }
 
        re += c
 
    } // switch
  } // for
 
 
  // handle the case where we left a class open.
  // "[abc" is valid, equivalent to "\[abc"
  if (inClass) {
    // split where the last [ was, and escape it
    // this is a huge pita.  We now have to re-walk
    // the contents of the would-be class to re-translate
    // any characters that were passed through as-is
    var cs = pattern.substr(classStart + 1)
      , sp = this.parse(cs, SUBPARSE)
    re = re.substr(0, reClassStart) + "\\[" + sp[0]
    hasMagic = hasMagic || sp[1]
  }
 
  // handle the case where we had a +( thing at the *end*
  // of the pattern.
  // each pattern list stack adds 3 chars, and we need to go through
  // and escape any | chars that were passed through as-is for the regexp.
  // Go through and escape them, taking care not to double-escape any
  // | chars that were already escaped.
  var pl
  while (pl = patternListStack.pop()) {
    var tail = re.slice(pl.reStart + 3)
    // maybe some even number of \, then maybe 1 \, followed by a |
    tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
      if (!$2) {
        // the | isn't already escaped, so escape it.
        $2 = "\\"
      }
 
      // need to escape all those slashes *again*, without escaping the
      // one that we need for escaping the | character.  As it works out,
      // escaping an even number of slashes can be done by simply repeating
      // it exactly after itself.  That's why this trick works.
      //
      // I am sorry that you have to see this.
      return $1 + $1 + $2 + "|"
    })
 
    this.debug("tail=%j\n   %s", tail, tail)
    var t = pl.type === "*" ? star
          : pl.type === "?" ? qmark
          : "\\" + pl.type
 
    hasMagic = true
    re = re.slice(0, pl.reStart)
       + t + "\\("
       + tail
  }
 
  // handle trailing things that only matter at the very end.
  clearStateChar()
  if (escaping) {
    // trailing \\
    re += "\\\\"
  }
 
  // only need to apply the nodot start if the re starts with
  // something that could conceivably capture a dot
  var addPatternStart = false
  switch (re.charAt(0)) {
    case ".":
    case "[":
    case "(": addPatternStart = true
  }
 
  // if the re is not "" at this point, then we need to make sure
  // it doesn't match against an empty path part.
  // Otherwise a/* will match a/, which it should not.
  if (re !== "" && hasMagic) re = "(?=.)" + re
 
  if (addPatternStart) re = patternStart + re
 
  // parsing just a piece of a larger pattern.
  if (isSub === SUBPARSE) {
    return [ re, hasMagic ]
  }
 
  // skip the regexp for non-magical patterns
  // unescape anything in it, though, so that it'll be
  // an exact match against a file etc.
  if (!hasMagic) {
    return globUnescape(pattern)
  }
 
  var flags = options.nocase ? "i" : ""
    , regExp = new RegExp("^" + re + "$", flags)
 
  regExp._glob = pattern
  regExp._src = re
 
  return regExp
}
 
minimatch.makeRe = function (pattern, options) {
  return new Minimatch(pattern, options || {}).makeRe()
}
 
Minimatch.prototype.makeRe = makeRe
function makeRe () {
  if (this.regexp || this.regexp === false) return this.regexp
 
  // at this point, this.set is a 2d array of partial
  // pattern strings, or "**".
  //
  // It's better to use .match().  This function shouldn't
  // be used, really, but it's pretty convenient sometimes,
  // when you just want to work with a regex.
  var set = this.set
 
  if (!set.length) return this.regexp = false
  var options = this.options
 
  var twoStar = options.noglobstar ? star
      : options.dot ? twoStarDot
      : twoStarNoDot
    , flags = options.nocase ? "i" : ""
 
  var re = set.map(function (pattern) {
    return pattern.map(function (p) {
      return (p === GLOBSTAR) ? twoStar
           : (typeof p === "string") ? regExpEscape(p)
           : p._src
    }).join("\\\/")
  }).join("|")
 
  // must match entire pattern
  // ending in a * or ** will make it less strict.
  re = "^(?:" + re + ")$"
 
  // can match anything, as long as it's not this.
  if (this.negate) re = "^(?!" + re + ").*$"
 
  try {
    return this.regexp = new RegExp(re, flags)
  } catch (ex) {
    return this.regexp = false
  }
}
 
minimatch.match = function (list, pattern, options) {
  options = options || {}
  var mm = new Minimatch(pattern, options)
  list = list.filter(function (f) {
    return mm.match(f)
  })
  if (mm.options.nonull && !list.length) {
    list.push(pattern)
  }
  return list
}
 
Minimatch.prototype.match = match
function match (f, partial) {
  this.debug("match", f, this.pattern)
  // short-circuit in the case of busted things.
  // comments, etc.
  if (this.comment) return false
  if (this.empty) return f === ""
 
  if (f === "/" && partial) return true
 
  var options = this.options
 
  // windows: need to use /, not \
  // On other platforms, \ is a valid (albeit bad) filename char.
  if (platform === "win32") {
    f = f.split("\\").join("/")
  }
 
  // treat the test path as a set of pathparts.
  f = f.split(slashSplit)
  this.debug(this.pattern, "split", f)
 
  // just ONE of the pattern sets in this.set needs to match
  // in order for it to be valid.  If negating, then just one
  // match means that we have failed.
  // Either way, return on the first hit.
 
  var set = this.set
  this.debug(this.pattern, "set", set)
 
  // Find the basename of the path by looking for the last non-empty segment
  var filename;
  for (var i = f.length - 1; i >= 0; i--) {
    filename = f[i]
    if (filename) break
  }
 
  for (var i = 0, l = set.length; i < l; i ++) {
    var pattern = set[i], file = f
    if (options.matchBase && pattern.length === 1) {
      file = [filename]
    }
    var hit = this.matchOne(file, pattern, partial)
    if (hit) {
      if (options.flipNegate) return true
      return !this.negate
    }
  }
 
  // didn't get any hits.  this is success if it's a negative
  // pattern, failure otherwise.
  if (options.flipNegate) return false
  return this.negate
}
 
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
  var options = this.options
 
  this.debug("matchOne",
              { "this": this
              , file: file
              , pattern: pattern })
 
  this.debug("matchOne", file.length, pattern.length)
 
  for ( var fi = 0
          , pi = 0
          , fl = file.length
          , pl = pattern.length
      ; (fi < fl) && (pi < pl)
      ; fi ++, pi ++ ) {
 
    this.debug("matchOne loop")
    var p = pattern[pi]
      , f = file[fi]
 
    this.debug(pattern, p, f)
 
    // should be impossible.
    // some invalid regexp stuff in the set.
    if (p === false) return false
 
    if (p === GLOBSTAR) {
      this.debug('GLOBSTAR', [pattern, p, f])
 
      // "**"
      // a/**/b/**/c would match the following:
      // a/b/x/y/z/c
      // a/x/y/z/b/c
      // a/b/x/b/x/c
      // a/b/c
      // To do this, take the rest of the pattern after
      // the **, and see if it would match the file remainder.
      // If so, return success.
      // If not, the ** "swallows" a segment, and try again.
      // This is recursively awful.
      //
      // a/**/b/**/c matching a/b/x/y/z/c
      // - a matches a
      // - doublestar
      //   - matchOne(b/x/y/z/c, b/**/c)
      //     - b matches b
      //     - doublestar
      //       - matchOne(x/y/z/c, c) -> no
      //       - matchOne(y/z/c, c) -> no
      //       - matchOne(z/c, c) -> no
      //       - matchOne(c, c) yes, hit
      var fr = fi
        , pr = pi + 1
      if (pr === pl) {
        this.debug('** at the end')
        // a ** at the end will just swallow the rest.
        // We have found a match.
        // however, it will not swallow /.x, unless
        // options.dot is set.
        // . and .. are *never* matched by **, for explosively
        // exponential reasons.
        for ( ; fi < fl; fi ++) {
          if (file[fi] === "." || file[fi] === ".." ||
              (!options.dot && file[fi].charAt(0) === ".")) return false
        }
        return true
      }
 
      // ok, let's see if we can swallow whatever we can.
      WHILE: while (fr < fl) {
        var swallowee = file[fr]
 
        this.debug('\nglobstar while',
                    file, fr, pattern, pr, swallowee)
 
        // XXX remove this slice.  Just pass the start index.
        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
          this.debug('globstar found match!', fr, fl, swallowee)
          // found a match.
          return true
        } else {
          // can't swallow "." or ".." ever.
          // can only swallow ".foo" when explicitly asked.
          if (swallowee === "." || swallowee === ".." ||
              (!options.dot && swallowee.charAt(0) === ".")) {
            this.debug("dot detected!", file, fr, pattern, pr)
            break WHILE
          }
 
          // ** swallows a segment, and continue.
          this.debug('globstar swallow a segment, and continue')
          fr ++
        }
      }
      // no match was found.
      // However, in partial mode, we can't say this is necessarily over.
      // If there's more *pattern* left, then
      if (partial) {
        // ran out of file
        this.debug("\n>>> no match, partial?", file, fr, pattern, pr)
        if (fr === fl) return true
      }
      return false
    }
 
    // something other than **
    // non-magic patterns just have to match exactly
    // patterns with magic have been turned into regexps.
    var hit
    if (typeof p === "string") {
      if (options.nocase) {
        hit = f.toLowerCase() === p.toLowerCase()
      } else {
        hit = f === p
      }
      this.debug("string match", p, f, hit)
    } else {
      hit = f.match(p)
      this.debug("pattern match", p, f, hit)
    }
 
    if (!hit) return false
  }
 
  // Note: ending in / means that we'll get a final ""
  // at the end of the pattern.  This can only match a
  // corresponding "" at the end of the file.
  // If the file ends in /, then it can only match a
  // a pattern that ends in /, unless the pattern just
  // doesn't have any more for it. But, a/b/ should *not*
  // match "a/b/*", even though "" matches against the
  // [^/]*? pattern, except in partial mode, where it might
  // simply not be reached yet.
  // However, a/b/ should still satisfy a/*
 
  // now either we fell off the end of the pattern, or we're done.
  if (fi === fl && pi === pl) {
    // ran out of pattern and filename at the same time.
    // an exact hit!
    return true
  } else if (fi === fl) {
    // ran out of file, but still had pattern left.
    // this is ok if we're doing the match as part of
    // a glob fs traversal.
    return partial
  } else if (pi === pl) {
    // ran out of pattern, still have file left.
    // this is only acceptable if we're on the very last
    // empty segment of a file with a trailing slash.
    // a/* should match a/b/
    var emptyFileEnd = (fi === fl - 1) && (file[fi] === "")
    return emptyFileEnd
  }
 
  // should be unreachable.
  throw new Error("wtf?")
}
 
 
// replace stuff like \* with *
function globUnescape (s) {
  return s.replace(/\\(.)/g, "$1")
}
 
 
function regExpEscape (s) {
  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
}
 
})( typeof require === "function" ? require : null,
    this,
    typeof module === "object" ? module : null,
    typeof process === "object" ? process.platform : "win32"
  )
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/lru-cache/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/lru-cache/lib/

Statements: 25.82% (47 / 182)      Branches: 17.76% (19 / 107)      Functions: 10.34% (3 / 29)      Lines: 28.48% (47 / 165)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/lru-cache/lib/
File Statements Branches Functions Lines
lru-cache.js 25.82% (47 / 182) 17.76% (19 / 107) 10.34% (3 / 29) 28.48% (47 / 165)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js

Statements: 25.82% (47 / 182)      Branches: 17.76% (19 / 107)      Functions: 10.34% (3 / 29)      Lines: 28.48% (47 / 165)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 2761   1 1           1       1   1 1     1     1     1   1     1 1     1 1 1 1       1                     1                                             1           1         1                                   1                   1                   1 1           1 1 1 1 1 1         1       1       1                                                                     1                 1       1       1           1       1                           1                       1           1         1         1                     1                      
;(function () { // closure for web browsers
 
Eif (typeof module === 'object' && module.exports) {
  module.exports = LRUCache
} else {
  // just set the global for non-node platforms.
  this.LRUCache = LRUCache
}
 
function hOP (obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key)
}
 
function naiveLength () { return 1 }
 
function LRUCache (options) {
  Iif (!(this instanceof LRUCache))
    return new LRUCache(options)
 
  Iif (typeof options === 'number')
    options = { max: options }
 
  Iif (!options)
    options = {}
 
  this._max = options.max
  // Kind of weird to have a default max of Infinity, but oh well.
  Iif (!this._max || !(typeof this._max === "number") || this._max <= 0 )
    this._max = Infinity
 
  this._lengthCalculator = options.length || naiveLength
  Iif (typeof this._lengthCalculator !== "function")
    this._lengthCalculator = naiveLength
 
  this._allowStale = options.stale || false
  this._maxAge = options.maxAge || null
  this._dispose = options.dispose
  this.reset()
}
 
// resize the cache when the max changes.
Object.defineProperty(LRUCache.prototype, "max",
  { set : function (mL) {
      if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity
      this._max = mL
      if (this._length > this._max) trim(this)
    }
  , get : function () { return this._max }
  , enumerable : true
  })
 
// resize the cache when the lengthCalculator changes.
Object.defineProperty(LRUCache.prototype, "lengthCalculator",
  { set : function (lC) {
      if (typeof lC !== "function") {
        this._lengthCalculator = naiveLength
        this._length = this._itemCount
        for (var key in this._cache) {
          this._cache[key].length = 1
        }
      } else {
        this._lengthCalculator = lC
        this._length = 0
        for (var key in this._cache) {
          this._cache[key].length = this._lengthCalculator(this._cache[key].value)
          this._length += this._cache[key].length
        }
      }
 
      if (this._length > this._max) trim(this)
    }
  , get : function () { return this._lengthCalculator }
  , enumerable : true
  })
 
Object.defineProperty(LRUCache.prototype, "length",
  { get : function () { return this._length }
  , enumerable : true
  })
 
 
Object.defineProperty(LRUCache.prototype, "itemCount",
  { get : function () { return this._itemCount }
  , enumerable : true
  })
 
LRUCache.prototype.forEach = function (fn, thisp) {
  thisp = thisp || this
  var i = 0
  var itemCount = this._itemCount
 
  for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) {
    i++
    var hit = this._lruList[k]
    if (isStale(this, hit)) {
      del(this, hit)
      if (!this._allowStale) hit = undefined
    }
    if (hit) {
      fn.call(thisp, hit.value, hit.key, this)
    }
  }
}
 
LRUCache.prototype.keys = function () {
  var keys = new Array(this._itemCount)
  var i = 0
  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
    var hit = this._lruList[k]
    keys[i++] = hit.key
  }
  return keys
}
 
LRUCache.prototype.values = function () {
  var values = new Array(this._itemCount)
  var i = 0
  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
    var hit = this._lruList[k]
    values[i++] = hit.value
  }
  return values
}
 
LRUCache.prototype.reset = function () {
  Iif (this._dispose && this._cache) {
    for (var k in this._cache) {
      this._dispose(k, this._cache[k].value)
    }
  }
 
  this._cache = Object.create(null) // hash of items by key
  this._lruList = Object.create(null) // list of items in order of use recency
  this._mru = 0 // most recently used
  this._lru = 0 // least recently used
  this._length = 0 // number of items in the list
  this._itemCount = 0
}
 
// Provided for debugging/dev purposes only. No promises whatsoever that
// this API stays stable.
LRUCache.prototype.dump = function () {
  return this._cache
}
 
LRUCache.prototype.dumpLru = function () {
  return this._lruList
}
 
LRUCache.prototype.set = function (key, value, maxAge) {
  maxAge = maxAge || this._maxAge
  var now = maxAge ? Date.now() : 0
 
  if (hOP(this._cache, key)) {
    // dispose of the old one before overwriting
    if (this._dispose)
      this._dispose(key, this._cache[key].value)
 
    this._cache[key].now = now
    this._cache[key].maxAge = maxAge
    this._cache[key].value = value
    this.get(key)
    return true
  }
 
  var len = this._lengthCalculator(value)
  var hit = new Entry(key, value, this._mru++, len, now, maxAge)
 
  // oversized objects fall out of cache automatically.
  if (hit.length > this._max) {
    if (this._dispose) this._dispose(key, value)
    return false
  }
 
  this._length += hit.length
  this._lruList[hit.lu] = this._cache[key] = hit
  this._itemCount ++
 
  if (this._length > this._max)
    trim(this)
 
  return true
}
 
LRUCache.prototype.has = function (key) {
  if (!hOP(this._cache, key)) return false
  var hit = this._cache[key]
  if (isStale(this, hit)) {
    return false
  }
  return true
}
 
LRUCache.prototype.get = function (key) {
  return get(this, key, true)
}
 
LRUCache.prototype.peek = function (key) {
  return get(this, key, false)
}
 
LRUCache.prototype.pop = function () {
  var hit = this._lruList[this._lru]
  del(this, hit)
  return hit || null
}
 
LRUCache.prototype.del = function (key) {
  del(this, this._cache[key])
}
 
function get (self, key, doUse) {
  var hit = self._cache[key]
  if (hit) {
    if (isStale(self, hit)) {
      del(self, hit)
      if (!self._allowStale) hit = undefined
    } else {
      if (doUse) use(self, hit)
    }
    if (hit) hit = hit.value
  }
  return hit
}
 
function isStale(self, hit) {
  if (!hit || (!hit.maxAge && !self._maxAge)) return false
  var stale = false;
  var diff = Date.now() - hit.now
  if (hit.maxAge) {
    stale = diff > hit.maxAge
  } else {
    stale = self._maxAge && (diff > self._maxAge)
  }
  return stale;
}
 
function use (self, hit) {
  shiftLU(self, hit)
  hit.lu = self._mru ++
  self._lruList[hit.lu] = hit
}
 
function trim (self) {
  while (self._lru < self._mru && self._length > self._max)
    del(self, self._lruList[self._lru])
}
 
function shiftLU (self, hit) {
  delete self._lruList[ hit.lu ]
  while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++
}
 
function del (self, hit) {
  if (hit) {
    if (self._dispose) self._dispose(hit.key, hit.value)
    self._length -= hit.length
    self._itemCount --
    delete self._cache[ hit.key ]
    shiftLU(self, hit)
  }
}
 
// classy, since V8 prefers predictable objects.
function Entry (key, value, lu, length, now, maxAge) {
  this.key = key
  this.value = value
  this.lu = lu
  this.length = length
  this.now = now
  if (maxAge) this.maxAge = maxAge
}
 
})()
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/sigmund/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/sigmund/

Statements: 10.71% (3 / 28)      Branches: 0% (0 / 23)      Functions: 0% (0 / 3)      Lines: 12.5% (3 / 24)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/sigmund/
File Statements Branches Functions Lines
sigmund.js 10.71% (3 / 28) 0% (0 / 23) 0% (0 / 3) 12.5% (3 / 24)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/sigmund/sigmund.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/minimatch/node_modules/sigmund/sigmund.js

Statements: 10.71% (3 / 28)      Branches: 0% (0 / 23)      Functions: 0% (0 / 3)      Lines: 12.5% (3 / 24)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411 1           1                                                                  
module.exports = sigmund
function sigmund (subject, maxSessions) {
    maxSessions = maxSessions || 10;
    var notes = [];
    var analysis = '';
    var RE = RegExp;
 
    function psychoAnalyze (subject, session) {
        if (session > maxSessions) return;
 
        if (typeof subject === 'function' ||
            typeof subject === 'undefined') {
            return;
        }
 
        if (typeof subject !== 'object' || !subject ||
            (subject instanceof RE)) {
            analysis += subject;
            return;
        }
 
        if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
 
        notes.push(subject);
        analysis += '{';
        Object.keys(subject).forEach(function (issue, _, __) {
            // pseudo-private values.  skip those.
            if (issue.charAt(0) === '_') return;
            var to = typeof subject[issue];
            if (to === 'function' || to === 'undefined') return;
            analysis += issue;
            psychoAnalyze(subject[issue], session + 1);
        });
    }
    psychoAnalyze(subject, 0);
    return analysis;
}
 
// vim: set softtabstop=4 shiftwidth=4:
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/mkdirp/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/mkdirp/

Statements: 10.34% (6 / 58)      Branches: 0% (0 / 42)      Functions: 0% (0 / 6)      Lines: 11.32% (6 / 53)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/mkdirp/
File Statements Branches Functions Lines
index.js 10.34% (6 / 58) 0% (0 / 42) 0% (0 / 6) 11.32% (6 / 53)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/mkdirp/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/mkdirp/index.js

Statements: 10.34% (6 / 58)      Branches: 0% (0 / 42)      Functions: 0% (0 / 6)      Lines: 11.32% (6 / 53)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 1001 1 1   1   1                                                                                               1                                                                                          
var path = require('path');
var fs = require('fs');
var _0777 = parseInt('0777', 8);
 
module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
 
function mkdirP (p, opts, f, made) {
    if (typeof opts === 'function') {
        f = opts;
        opts = {};
    }
    else if (!opts || typeof opts !== 'object') {
        opts = { mode: opts };
    }
    
    var mode = opts.mode;
    var xfs = opts.fs || fs;
    
    if (mode === undefined) {
        mode = _0777 & (~process.umask());
    }
    if (!made) made = null;
    
    var cb = f || function () {};
    p = path.resolve(p);
    
    xfs.mkdir(p, mode, function (er) {
        if (!er) {
            made = made || p;
            return cb(null, made);
        }
        switch (er.code) {
            case 'ENOENT':
                mkdirP(path.dirname(p), opts, function (er, made) {
                    if (er) cb(er, made);
                    else mkdirP(p, opts, cb, made);
                });
                break;
 
            // In the case of any other error, just see if there's a dir
            // there already.  If so, then hooray!  If not, then something
            // is borked.
            default:
                xfs.stat(p, function (er2, stat) {
                    // if the stat fails, then that's super weird.
                    // let the original error be the failure reason.
                    if (er2 || !stat.isDirectory()) cb(er, made)
                    else cb(null, made);
                });
                break;
        }
    });
}
 
mkdirP.sync = function sync (p, opts, made) {
    if (!opts || typeof opts !== 'object') {
        opts = { mode: opts };
    }
    
    var mode = opts.mode;
    var xfs = opts.fs || fs;
    
    if (mode === undefined) {
        mode = _0777 & (~process.umask());
    }
    if (!made) made = null;
 
    p = path.resolve(p);
 
    try {
        xfs.mkdirSync(p, mode);
        made = made || p;
    }
    catch (err0) {
        switch (err0.code) {
            case 'ENOENT' :
                made = sync(path.dirname(p), opts, made);
                sync(p, opts, made);
                break;
 
            // In the case of any other error, just see if there's a dir
            // there already.  If so, then hooray!  If not, then something
            // is borked.
            default:
                var stat;
                try {
                    stat = xfs.statSync(p);
                }
                catch (err1) {
                    throw err0;
                }
                if (!stat.isDirectory()) throw err0;
                break;
        }
    }
 
    return made;
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/

Statements: 100% (7 / 7)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (7 / 7)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/readable-stream/
File Statements Branches Functions Lines
readable.js 100% (7 / 7) 100% (0 / 0) 100% (0 / 0) 100% (7 / 7)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/readable.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/readable.js

Statements: 100% (7 / 7)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (7 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 91 1 1 1 1 1 1    
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('stream');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/

Statements: 14.8% (123 / 831)      Branches: 1.41% (7 / 497)      Functions: 1.96% (2 / 102)      Lines: 14.89% (123 / 826)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/
File Statements Branches Functions Lines
_stream_duplex.js 44.12% (15 / 34) 13.64% (3 / 22) 40% (2 / 5) 45.45% (15 / 33)
_stream_passthrough.js 63.64% (7 / 11) 0% (0 / 2) 0% (0 / 2) 63.64% (7 / 11)
_stream_readable.js 11.38% (56 / 492) 1.23% (4 / 325) 0% (0 / 53) 11.48% (56 / 488)
_stream_transform.js 18.31% (13 / 71) 0% (0 / 32) 0% (0 / 11) 18.31% (13 / 71)
_stream_writable.js 14.35% (32 / 223) 0% (0 / 116) 0% (0 / 31) 14.35% (32 / 223)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_duplex.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_duplex.js

Statements: 44.12% (15 / 34)      Branches: 13.64% (3 / 22)      Functions: 40% (2 / 5)      Lines: 45.45% (15 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91                                                    1     1                 1 1     1 1   1   1 7 6     1                                         1                     1 1 7        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
 
module.exports = Duplex;
 
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) keys.push(key);
  return keys;
}
/*</replacement>*/
 
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
 
util.inherits(Duplex, Readable);
 
forEach(objectKeys(Writable.prototype), function(method) {
  if (!Duplex.prototype[method])
    Duplex.prototype[method] = Writable.prototype[method];
});
 
function Duplex(options) {
  if (!(this instanceof Duplex))
    return new Duplex(options);
 
  Readable.call(this, options);
  Writable.call(this, options);
 
  if (options && options.readable === false)
    this.readable = false;
 
  if (options && options.writable === false)
    this.writable = false;
 
  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false)
    this.allowHalfOpen = false;
 
  this.once('end', onend);
}
 
// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended)
    return;
 
  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(this.end.bind(this));
}
 
function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_passthrough.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_passthrough.js

Statements: 63.64% (7 / 11)      Branches: 0% (0 / 2)      Functions: 0% (0 / 2)      Lines: 63.64% (7 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                                  1   1     1 1     1   1             1        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
 
module.exports = PassThrough;
 
var Transform = require('./_stream_transform');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
util.inherits(PassThrough, Transform);
 
function PassThrough(options) {
  if (!(this instanceof PassThrough))
    return new PassThrough(options);
 
  Transform.call(this, options);
}
 
PassThrough.prototype._transform = function(chunk, encoding, cb) {
  cb(null, chunk);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_readable.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_readable.js

Statements: 11.38% (56 / 492)      Branches: 1.23% (4 / 325)      Functions: 0% (0 / 53)      Lines: 11.48% (56 / 488)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953                                          1     1         1     1   1     1         1     1 1     1       1 1 1             1   1                                                                                                                                       1                                   1                             1         1                                                                                                               1               1                 1 1                       1                                                                           1                                                                                                                                                                                                                                     1                       1                                 1                             1                         1                 1                                     1       1                                                         1             1                       1                                             1                         1                                     1         1             1                                 1                           1                                                                                                                 1                                                         1       1                           1                 1               1                   1                         1                                                                                                                           1       1                                                                                                                               1                                         1           1              
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
module.exports = Readable;
 
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
 
 
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
 
Readable.ReadableState = ReadableState;
 
var EE = require('events').EventEmitter;
 
/*<replacement>*/
Iif (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/
 
var Stream = require('stream');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var StringDecoder;
 
 
/*<replacement>*/
var debug = require('util');
Eif (debug && debug.debuglog) {
  debug = debug.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/
 
 
util.inherits(Readable, Stream);
 
function ReadableState(options, stream) {
  var Duplex = require('./_stream_duplex');
 
  options = options || {};
 
  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  this.buffer = [];
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
 
 
  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;
 
  if (stream instanceof Duplex)
    this.objectMode = this.objectMode || !!options.readableObjectMode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // when piping, we only care about 'readable' events that happen
  // after read()ing all the bytes and not getting any pushback.
  this.ranOut = false;
 
  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;
 
  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;
 
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder)
      StringDecoder = require('string_decoder/').StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}
 
function Readable(options) {
  var Duplex = require('./_stream_duplex');
 
  if (!(this instanceof Readable))
    return new Readable(options);
 
  this._readableState = new ReadableState(options, this);
 
  // legacy
  this.readable = true;
 
  Stream.call(this);
}
 
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
  var state = this._readableState;
 
  if (util.isString(chunk) && !state.objectMode) {
    encoding = encoding || state.defaultEncoding;
    if (encoding !== state.encoding) {
      chunk = new Buffer(chunk, encoding);
      encoding = '';
    }
  }
 
  return readableAddChunk(this, state, chunk, encoding, false);
};
 
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
  var state = this._readableState;
  return readableAddChunk(this, state, chunk, '', true);
};
 
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  var er = chunkInvalid(state, chunk);
  if (er) {
    stream.emit('error', er);
  } else if (util.isNullOrUndefined(chunk)) {
    state.reading = false;
    if (!state.ended)
      onEofChunk(stream, state);
  } else if (state.objectMode || chunk && chunk.length > 0) {
    if (state.ended && !addToFront) {
      var e = new Error('stream.push() after EOF');
      stream.emit('error', e);
    } else if (state.endEmitted && addToFront) {
      var e = new Error('stream.unshift() after end event');
      stream.emit('error', e);
    } else {
      if (state.decoder && !addToFront && !encoding)
        chunk = state.decoder.write(chunk);
 
      if (!addToFront)
        state.reading = false;
 
      // if we want the data now, just emit it.
      if (state.flowing && state.length === 0 && !state.sync) {
        stream.emit('data', chunk);
        stream.read(0);
      } else {
        // update the buffer info.
        state.length += state.objectMode ? 1 : chunk.length;
        if (addToFront)
          state.buffer.unshift(chunk);
        else
          state.buffer.push(chunk);
 
        if (state.needReadable)
          emitReadable(stream);
      }
 
      maybeReadMore(stream, state);
    }
  } else if (!addToFront) {
    state.reading = false;
  }
 
  return needMoreData(state);
}
 
 
 
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended &&
         (state.needReadable ||
          state.length < state.highWaterMark ||
          state.length === 0);
}
 
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
  if (!StringDecoder)
    StringDecoder = require('string_decoder/').StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
  return this;
};
 
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2
    n--;
    for (var p = 1; p < 32; p <<= 1) n |= n >> p;
    n++;
  }
  return n;
}
 
function howMuchToRead(n, state) {
  if (state.length === 0 && state.ended)
    return 0;
 
  if (state.objectMode)
    return n === 0 ? 0 : 1;
 
  if (isNaN(n) || util.isNull(n)) {
    // only flow one buffer at a time
    if (state.flowing && state.buffer.length)
      return state.buffer[0].length;
    else
      return state.length;
  }
 
  if (n <= 0)
    return 0;
 
  // If we're asking for more than the target buffer level,
  // then raise the water mark.  Bump up to the next highest
  // power of 2, to prevent increasing it excessively in tiny
  // amounts.
  if (n > state.highWaterMark)
    state.highWaterMark = roundUpToNextPowerOf2(n);
 
  // don't have that much.  return null, unless we've ended.
  if (n > state.length) {
    if (!state.ended) {
      state.needReadable = true;
      return 0;
    } else
      return state.length;
  }
 
  return n;
}
 
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
  debug('read', n);
  var state = this._readableState;
  var nOrig = n;
 
  if (!util.isNumber(n) || n > 0)
    state.emittedReadable = false;
 
  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 &&
      state.needReadable &&
      (state.length >= state.highWaterMark || state.ended)) {
    debug('read: emitReadable', state.length, state.ended);
    if (state.length === 0 && state.ended)
      endReadable(this);
    else
      emitReadable(this);
    return null;
  }
 
  n = howMuchToRead(n, state);
 
  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    if (state.length === 0)
      endReadable(this);
    return null;
  }
 
  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.
 
  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
  debug('need readable', doRead);
 
  // if we currently have less than the highWaterMark, then also read some
  if (state.length === 0 || state.length - n < state.highWaterMark) {
    doRead = true;
    debug('length less than watermark', doRead);
  }
 
  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading) {
    doRead = false;
    debug('reading or ended', doRead);
  }
 
  if (doRead) {
    debug('do read');
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0)
      state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
  }
 
  // If _read pushed data synchronously, then `reading` will be false,
  // and we need to re-evaluate how much data we can return to the user.
  if (doRead && !state.reading)
    n = howMuchToRead(nOrig, state);
 
  var ret;
  if (n > 0)
    ret = fromList(n, state);
  else
    ret = null;
 
  if (util.isNull(ret)) {
    state.needReadable = true;
    n = 0;
  }
 
  state.length -= n;
 
  // If we have nothing in the buffer, then we want to know
  // as soon as we *do* get something into the buffer.
  if (state.length === 0 && !state.ended)
    state.needReadable = true;
 
  // If we tried to read() past the EOF, then emit end on the next tick.
  if (nOrig !== n && state.ended && state.length === 0)
    endReadable(this);
 
  if (!util.isNull(ret))
    this.emit('data', ret);
 
  return ret;
};
 
function chunkInvalid(state, chunk) {
  var er = null;
  if (!util.isBuffer(chunk) &&
      !util.isString(chunk) &&
      !util.isNullOrUndefined(chunk) &&
      !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}
 
 
function onEofChunk(stream, state) {
  if (state.decoder && !state.ended) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;
 
  // emit 'readable' now to make sure it gets picked up.
  emitReadable(stream);
}
 
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (!state.emittedReadable) {
    debug('emitReadable', state.flowing);
    state.emittedReadable = true;
    if (state.sync)
      process.nextTick(function() {
        emitReadable_(stream);
      });
    else
      emitReadable_(stream);
  }
}
 
function emitReadable_(stream) {
  debug('emit readable');
  stream.emit('readable');
  flow(stream);
}
 
 
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    process.nextTick(function() {
      maybeReadMore_(stream, state);
    });
  }
}
 
function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended &&
         state.length < state.highWaterMark) {
    debug('maybeReadMore read 0');
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;
    else
      len = state.length;
  }
  state.readingMore = false;
}
 
// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
  this.emit('error', new Error('not implemented'));
};
 
Readable.prototype.pipe = function(dest, pipeOpts) {
  var src = this;
  var state = this._readableState;
 
  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
 
  var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
              dest !== process.stdout &&
              dest !== process.stderr;
 
  var endFn = doEnd ? onend : cleanup;
  if (state.endEmitted)
    process.nextTick(endFn);
  else
    src.once('end', endFn);
 
  dest.on('unpipe', onunpipe);
  function onunpipe(readable) {
    debug('onunpipe');
    if (readable === src) {
      cleanup();
    }
  }
 
  function onend() {
    debug('onend');
    dest.end();
  }
 
  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);
 
  function cleanup() {
    debug('cleanup');
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', cleanup);
    src.removeListener('data', ondata);
 
    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (state.awaitDrain &&
        (!dest._writableState || dest._writableState.needDrain))
      ondrain();
  }
 
  src.on('data', ondata);
  function ondata(chunk) {
    debug('ondata');
    var ret = dest.write(chunk);
    if (false === ret) {
      debug('false write response, pause',
            src._readableState.awaitDrain);
      src._readableState.awaitDrain++;
      src.pause();
    }
  }
 
  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    debug('onerror', er);
    unpipe();
    dest.removeListener('error', onerror);
    if (EE.listenerCount(dest, 'error') === 0)
      dest.emit('error', er);
  }
  // This is a brutally ugly hack to make sure that our error handler
  // is attached before any userland ones.  NEVER DO THIS.
  if (!dest._events || !dest._events.error)
    dest.on('error', onerror);
  else if (isArray(dest._events.error))
    dest._events.error.unshift(onerror);
  else
    dest._events.error = [onerror, dest._events.error];
 
 
 
  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    debug('onfinish');
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);
 
  function unpipe() {
    debug('unpipe');
    src.unpipe(dest);
  }
 
  // tell the dest that it's being piped to
  dest.emit('pipe', src);
 
  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    debug('pipe resume');
    src.resume();
  }
 
  return dest;
};
 
function pipeOnDrain(src) {
  return function() {
    var state = src._readableState;
    debug('pipeOnDrain', state.awaitDrain);
    if (state.awaitDrain)
      state.awaitDrain--;
    if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
      state.flowing = true;
      flow(src);
    }
  };
}
 
 
Readable.prototype.unpipe = function(dest) {
  var state = this._readableState;
 
  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0)
    return this;
 
  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes)
      return this;
 
    if (!dest)
      dest = state.pipes;
 
    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
    if (dest)
      dest.emit('unpipe', this);
    return this;
  }
 
  // slow case. multiple pipe destinations.
 
  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    state.flowing = false;
 
    for (var i = 0; i < len; i++)
      dests[i].emit('unpipe', this);
    return this;
  }
 
  // try to find the right one.
  var i = indexOf(state.pipes, dest);
  if (i === -1)
    return this;
 
  state.pipes.splice(i, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1)
    state.pipes = state.pipes[0];
 
  dest.emit('unpipe', this);
 
  return this;
};
 
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);
 
  // If listening to data, and it has not explicitly been paused,
  // then call resume to start the flow of data on the next tick.
  if (ev === 'data' && false !== this._readableState.flowing) {
    this.resume();
  }
 
  if (ev === 'readable' && this.readable) {
    var state = this._readableState;
    if (!state.readableListening) {
      state.readableListening = true;
      state.emittedReadable = false;
      state.needReadable = true;
      if (!state.reading) {
        var self = this;
        process.nextTick(function() {
          debug('readable nexttick read 0');
          self.read(0);
        });
      } else if (state.length) {
        emitReadable(this, state);
      }
    }
  }
 
  return res;
};
Readable.prototype.addListener = Readable.prototype.on;
 
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
  var state = this._readableState;
  if (!state.flowing) {
    debug('resume');
    state.flowing = true;
    if (!state.reading) {
      debug('resume read 0');
      this.read(0);
    }
    resume(this, state);
  }
  return this;
};
 
function resume(stream, state) {
  if (!state.resumeScheduled) {
    state.resumeScheduled = true;
    process.nextTick(function() {
      resume_(stream, state);
    });
  }
}
 
function resume_(stream, state) {
  state.resumeScheduled = false;
  stream.emit('resume');
  flow(stream);
  if (state.flowing && !state.reading)
    stream.read(0);
}
 
Readable.prototype.pause = function() {
  debug('call pause flowing=%j', this._readableState.flowing);
  if (false !== this._readableState.flowing) {
    debug('pause');
    this._readableState.flowing = false;
    this.emit('pause');
  }
  return this;
};
 
function flow(stream) {
  var state = stream._readableState;
  debug('flow', state.flowing);
  if (state.flowing) {
    do {
      var chunk = stream.read();
    } while (null !== chunk && state.flowing);
  }
}
 
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
  var state = this._readableState;
  var paused = false;
 
  var self = this;
  stream.on('end', function() {
    debug('wrapped end');
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length)
        self.push(chunk);
    }
 
    self.push(null);
  });
 
  stream.on('data', function(chunk) {
    debug('wrapped data');
    if (state.decoder)
      chunk = state.decoder.write(chunk);
    if (!chunk || !state.objectMode && !chunk.length)
      return;
 
    var ret = self.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });
 
  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
      this[i] = function(method) { return function() {
        return stream[method].apply(stream, arguments);
      }}(i);
    }
  }
 
  // proxy certain important events.
  var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  forEach(events, function(ev) {
    stream.on(ev, self.emit.bind(self, ev));
  });
 
  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  self._read = function(n) {
    debug('wrapped _read', n);
    if (paused) {
      paused = false;
      stream.resume();
    }
  };
 
  return self;
};
 
 
 
// exposed for testing purposes only.
Readable._fromList = fromList;
 
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
  var list = state.buffer;
  var length = state.length;
  var stringMode = !!state.decoder;
  var objectMode = !!state.objectMode;
  var ret;
 
  // nothing in the list, definitely empty.
  if (list.length === 0)
    return null;
 
  if (length === 0)
    ret = null;
  else if (objectMode)
    ret = list.shift();
  else if (!n || n >= length) {
    // read it all, truncate the array.
    if (stringMode)
      ret = list.join('');
    else
      ret = Buffer.concat(list, length);
    list.length = 0;
  } else {
    // read just some of it.
    if (n < list[0].length) {
      // just take a part of the first list item.
      // slice is the same for buffers and strings.
      var buf = list[0];
      ret = buf.slice(0, n);
      list[0] = buf.slice(n);
    } else if (n === list[0].length) {
      // first list is a perfect match
      ret = list.shift();
    } else {
      // complex case.
      // we have enough to cover it, but it spans past the first buffer.
      if (stringMode)
        ret = '';
      else
        ret = new Buffer(n);
 
      var c = 0;
      for (var i = 0, l = list.length; i < l && c < n; i++) {
        var buf = list[0];
        var cpy = Math.min(n - c, buf.length);
 
        if (stringMode)
          ret += buf.slice(0, cpy);
        else
          buf.copy(ret, c, 0, cpy);
 
        if (cpy < buf.length)
          list[0] = buf.slice(cpy);
        else
          list.shift();
 
        c += cpy;
      }
    }
  }
 
  return ret;
}
 
function endReadable(stream) {
  var state = stream._readableState;
 
  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0)
    throw new Error('endReadable called on non-empty stream');
 
  if (!state.endEmitted) {
    state.ended = true;
    process.nextTick(function() {
      // Check that we didn't get one last unshift.
      if (!state.endEmitted && state.length === 0) {
        state.endEmitted = true;
        stream.readable = false;
        stream.emit('end');
      }
    });
  }
}
 
function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
function indexOf (xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_transform.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_transform.js

Statements: 18.31% (13 / 71)      Branches: 0% (0 / 32)      Functions: 0% (0 / 11)      Lines: 18.31% (13 / 71)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                                                                                                                1   1     1 1     1     1                     1                                                   1                                                         1                             1       1                                 1                           1                                    
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 
// a transform stream is a readable/writable stream where you do
// something with the data.  Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored.  (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation.  For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes.  When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up.  When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer.  When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks.  If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk.  However,
// a pathological inflate type of transform can cause excessive buffering
// here.  For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output.  In this case, you could write a very small
// amount of input, and end up with a very large amount of output.  In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform.  A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
 
module.exports = Transform;
 
var Duplex = require('./_stream_duplex');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
util.inherits(Transform, Duplex);
 
 
function TransformState(options, stream) {
  this.afterTransform = function(er, data) {
    return afterTransform(stream, er, data);
  };
 
  this.needTransform = false;
  this.transforming = false;
  this.writecb = null;
  this.writechunk = null;
}
 
function afterTransform(stream, er, data) {
  var ts = stream._transformState;
  ts.transforming = false;
 
  var cb = ts.writecb;
 
  if (!cb)
    return stream.emit('error', new Error('no writecb in Transform class'));
 
  ts.writechunk = null;
  ts.writecb = null;
 
  if (!util.isNullOrUndefined(data))
    stream.push(data);
 
  if (cb)
    cb(er);
 
  var rs = stream._readableState;
  rs.reading = false;
  if (rs.needReadable || rs.length < rs.highWaterMark) {
    stream._read(rs.highWaterMark);
  }
}
 
 
function Transform(options) {
  if (!(this instanceof Transform))
    return new Transform(options);
 
  Duplex.call(this, options);
 
  this._transformState = new TransformState(options, this);
 
  // when the writable side finishes, then flush out anything remaining.
  var stream = this;
 
  // start out asking for a readable event once data is transformed.
  this._readableState.needReadable = true;
 
  // we have implemented the _read method, and done the other things
  // that Readable wants before the first _read call, so unset the
  // sync guard flag.
  this._readableState.sync = false;
 
  this.once('prefinish', function() {
    if (util.isFunction(this._flush))
      this._flush(function(er) {
        done(stream, er);
      });
    else
      done(stream);
  });
}
 
Transform.prototype.push = function(chunk, encoding) {
  this._transformState.needTransform = false;
  return Duplex.prototype.push.call(this, chunk, encoding);
};
 
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error, then that'll put the hurt on the whole operation.  If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
  throw new Error('not implemented');
};
 
Transform.prototype._write = function(chunk, encoding, cb) {
  var ts = this._transformState;
  ts.writecb = cb;
  ts.writechunk = chunk;
  ts.writeencoding = encoding;
  if (!ts.transforming) {
    var rs = this._readableState;
    if (ts.needTransform ||
        rs.needReadable ||
        rs.length < rs.highWaterMark)
      this._read(rs.highWaterMark);
  }
};
 
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
  var ts = this._transformState;
 
  if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
    ts.transforming = true;
    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  } else {
    // mark that we need a transform, so that any data that comes in
    // will get processed, now that we've asked for it.
    ts.needTransform = true;
  }
};
 
 
function done(stream, er) {
  if (er)
    return stream.emit('error', er);
 
  // if there's nothing in the write buffer, then that means
  // that nothing more will ever be provided
  var ws = stream._writableState;
  var ts = stream._transformState;
 
  if (ws.length)
    throw new Error('calling transform done when ws.length != 0');
 
  if (ts.transforming)
    throw new Error('calling transform done when still transforming');
 
  return stream.push(null);
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_writable.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/lib/_stream_writable.js

Statements: 14.35% (32 / 223)      Branches: 0% (0 / 116)      Functions: 0% (0 / 31)      Lines: 14.35% (32 / 223)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479                                                  1     1     1       1 1     1   1   1           1                                                                                                                                                                               1                                 1         1                           1                               1                                                     1           1                             1                       1                                         1                       1                             1             1                                                           1                     1                 1                                                                                                     1         1   1                                                     1             1             1                         1                        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
 
module.exports = Writable;
 
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
 
Writable.WritableState = WritableState;
 
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Stream = require('stream');
 
util.inherits(Writable, Stream);
 
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
}
 
function WritableState(options, stream) {
  var Duplex = require('./_stream_duplex');
 
  options = options || {};
 
  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
 
  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;
 
  if (stream instanceof Duplex)
    this.objectMode = this.objectMode || !!options.writableObjectMode;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;
 
  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;
 
  // a flag to see when we're in the middle of a write.
  this.writing = false;
 
  // when true all writes will be buffered until .uncork() call
  this.corked = 0;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;
 
  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function(er) {
    onwrite(stream, er);
  };
 
  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;
 
  // the amount that is being written when _write is called.
  this.writelen = 0;
 
  this.buffer = [];
 
  // number of pending user-supplied write callbacks
  // this must be 0 before 'finish' can be emitted
  this.pendingcb = 0;
 
  // emit prefinish if the only thing we're waiting for is _write cbs
  // This is relevant for synchronous Transform streams
  this.prefinished = false;
 
  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;
}
 
function Writable(options) {
  var Duplex = require('./_stream_duplex');
 
  // Writable ctor is applied to Duplexes, though they're not
  // instanceof Writable, they're instanceof Readable.
  if (!(this instanceof Writable) && !(this instanceof Duplex))
    return new Writable(options);
 
  this._writableState = new WritableState(options, this);
 
  // legacy.
  this.writable = true;
 
  Stream.call(this);
}
 
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
  this.emit('error', new Error('Cannot pipe. Not readable.'));
};
 
 
function writeAfterEnd(stream, state, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  process.nextTick(function() {
    cb(er);
  });
}
 
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  if (!util.isBuffer(chunk) &&
      !util.isString(chunk) &&
      !util.isNullOrUndefined(chunk) &&
      !state.objectMode) {
    var er = new TypeError('Invalid non-string/buffer chunk');
    stream.emit('error', er);
    process.nextTick(function() {
      cb(er);
    });
    valid = false;
  }
  return valid;
}
 
Writable.prototype.write = function(chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
 
  if (util.isFunction(encoding)) {
    cb = encoding;
    encoding = null;
  }
 
  if (util.isBuffer(chunk))
    encoding = 'buffer';
  else if (!encoding)
    encoding = state.defaultEncoding;
 
  if (!util.isFunction(cb))
    cb = function() {};
 
  if (state.ended)
    writeAfterEnd(this, state, cb);
  else if (validChunk(this, state, chunk, cb)) {
    state.pendingcb++;
    ret = writeOrBuffer(this, state, chunk, encoding, cb);
  }
 
  return ret;
};
 
Writable.prototype.cork = function() {
  var state = this._writableState;
 
  state.corked++;
};
 
Writable.prototype.uncork = function() {
  var state = this._writableState;
 
  if (state.corked) {
    state.corked--;
 
    if (!state.writing &&
        !state.corked &&
        !state.finished &&
        !state.bufferProcessing &&
        state.buffer.length)
      clearBuffer(this, state);
  }
};
 
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode &&
      state.decodeStrings !== false &&
      util.isString(chunk)) {
    chunk = new Buffer(chunk, encoding);
  }
  return chunk;
}
 
// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
  chunk = decodeChunk(state, chunk, encoding);
  if (util.isBuffer(chunk))
    encoding = 'buffer';
  var len = state.objectMode ? 1 : chunk.length;
 
  state.length += len;
 
  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret)
    state.needDrain = true;
 
  if (state.writing || state.corked)
    state.buffer.push(new WriteReq(chunk, encoding, cb));
  else
    doWrite(stream, state, false, len, chunk, encoding, cb);
 
  return ret;
}
 
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  if (writev)
    stream._writev(chunk, state.onwrite);
  else
    stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
 
function onwriteError(stream, state, sync, er, cb) {
  if (sync)
    process.nextTick(function() {
      state.pendingcb--;
      cb(er);
    });
  else {
    state.pendingcb--;
    cb(er);
  }
 
  stream._writableState.errorEmitted = true;
  stream.emit('error', er);
}
 
function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}
 
function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;
 
  onwriteStateUpdate(state);
 
  if (er)
    onwriteError(stream, state, sync, er, cb);
  else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(stream, state);
 
    if (!finished &&
        !state.corked &&
        !state.bufferProcessing &&
        state.buffer.length) {
      clearBuffer(stream, state);
    }
 
    if (sync) {
      process.nextTick(function() {
        afterWrite(stream, state, finished, cb);
      });
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}
 
function afterWrite(stream, state, finished, cb) {
  if (!finished)
    onwriteDrain(stream, state);
  state.pendingcb--;
  cb();
  finishMaybe(stream, state);
}
 
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}
 
 
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
 
  if (stream._writev && state.buffer.length > 1) {
    // Fast case, write everything using _writev()
    var cbs = [];
    for (var c = 0; c < state.buffer.length; c++)
      cbs.push(state.buffer[c].callback);
 
    // count the one we are adding, as well.
    // TODO(isaacs) clean this up
    state.pendingcb++;
    doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
      for (var i = 0; i < cbs.length; i++) {
        state.pendingcb--;
        cbs[i](err);
      }
    });
 
    // Clear buffer
    state.buffer = [];
  } else {
    // Slow case, write chunks one-by-one
    for (var c = 0; c < state.buffer.length; c++) {
      var entry = state.buffer[c];
      var chunk = entry.chunk;
      var encoding = entry.encoding;
      var cb = entry.callback;
      var len = state.objectMode ? 1 : chunk.length;
 
      doWrite(stream, state, false, len, chunk, encoding, cb);
 
      // if we didn't call the onwrite immediately, then
      // it means that we need to wait until it does.
      // also, that means that the chunk and cb are currently
      // being processed, so move the buffer counter past them.
      if (state.writing) {
        c++;
        break;
      }
    }
 
    if (c < state.buffer.length)
      state.buffer = state.buffer.slice(c);
    else
      state.buffer.length = 0;
  }
 
  state.bufferProcessing = false;
}
 
Writable.prototype._write = function(chunk, encoding, cb) {
  cb(new Error('not implemented'));
 
};
 
Writable.prototype._writev = null;
 
Writable.prototype.end = function(chunk, encoding, cb) {
  var state = this._writableState;
 
  if (util.isFunction(chunk)) {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (util.isFunction(encoding)) {
    cb = encoding;
    encoding = null;
  }
 
  if (!util.isNullOrUndefined(chunk))
    this.write(chunk, encoding);
 
  // .end() fully uncorks
  if (state.corked) {
    state.corked = 1;
    this.uncork();
  }
 
  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished)
    endWritable(this, state, cb);
};
 
 
function needFinish(stream, state) {
  return (state.ending &&
          state.length === 0 &&
          !state.finished &&
          !state.writing);
}
 
function prefinish(stream, state) {
  if (!state.prefinished) {
    state.prefinished = true;
    stream.emit('prefinish');
  }
}
 
function finishMaybe(stream, state) {
  var need = needFinish(stream, state);
  if (need) {
    if (state.pendingcb === 0) {
      prefinish(stream, state);
      state.finished = true;
      stream.emit('finish');
    } else
      prefinish(stream, state);
  }
  return need;
}
 
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished)
      process.nextTick(cb);
    else
      stream.once('finish', cb);
  }
  state.ended = true;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/core-util-is/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/core-util-is/lib/

Statements: 65.96% (31 / 47)      Branches: 0% (0 / 15)      Functions: 0% (0 / 16)      Lines: 65.96% (31 / 47)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/core-util-is/lib/
File Statements Branches Functions Lines
util.js 65.96% (31 / 47) 0% (0 / 15) 0% (0 / 16) 65.96% (31 / 47)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

Statements: 65.96% (31 / 47)      Branches: 0% (0 / 15)      Functions: 0% (0 / 16)      Lines: 65.96% (31 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108                                              1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1       1   1     1   1               1   1     1   1      
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;
 
function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
 
function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;
 
function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
 
function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;
 
function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;
 
function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
 
function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;
 
function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
 
function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
 
function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
 
function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
 
function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;
 
function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
 
function isBuffer(arg) {
  return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
 
function objectToString(o) {
  return Object.prototype.toString.call(o);
}
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/inherits/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/inherits/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/inherits/
File Statements Branches Functions Lines
inherits.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/inherits/inherits.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/inherits/inherits.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('util').inherits
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/isarray/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/isarray/

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/isarray/
File Statements Branches Functions Lines
index.js 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/isarray/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/readable-stream/node_modules/isarray/index.js

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 51        
module.exports = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/

Statements: 8.25% (73 / 885)      Branches: 0.47% (3 / 645)      Functions: 1.18% (1 / 85)      Lines: 8.3% (73 / 879)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/
File Statements Branches Functions Lines
index.js 28.21% (22 / 78) 7.14% (2 / 28) 7.69% (1 / 13) 28.21% (22 / 78)
request.js 6.32% (51 / 807) 0.16% (1 / 617) 0% (0 / 72) 6.37% (51 / 801)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/index.js

Statements: 28.21% (22 / 78)      Branches: 7.14% (2 / 28)      Functions: 7.69% (1 / 13)      Lines: 28.21% (22 / 78)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161                                1       1         1                                     1                           1 6 6               1 1 1 1 1 1   1       1       1                                                   1                                         1                             1 1 1     1                    
// Copyright 2010-2012 Mikeal Rogers
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
 
'use strict'
 
var extend                = require('util')._extend
  , cookies               = require('./lib/cookies')
  , helpers               = require('./lib/helpers')
 
var isFunction            = helpers.isFunction
  , paramsHaveRequestBody = helpers.paramsHaveRequestBody
 
 
// organize params for patch, post, put, head, del
function initParams(uri, options, callback) {
  if (typeof options === 'function') {
    callback = options
  }
 
  var params = {}
  if (typeof options === 'object') {
    params = extend({}, options)
    params = extend(params, {uri: uri})
  } else if (typeof uri === 'string') {
    params = extend({}, {uri: uri})
  } else {
    params = extend({}, uri)
  }
 
  params.callback = callback
  return params
}
 
function request (uri, options, callback) {
  if (typeof uri === 'undefined') {
    throw new Error('undefined is not a valid uri or options object.')
  }
 
  var params = initParams(uri, options, callback)
 
  if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
    throw new Error('HTTP HEAD requests MUST NOT include a request body.')
  }
 
  return new request.Request(params)
}
 
function verbFunc (verb) {
  var method = verb === 'del' ? 'DELETE' : verb.toUpperCase()
  return function (uri, options, callback) {
    var params = initParams(uri, options, callback)
    params.method = method
    return request(params, params.callback)
  }
}
 
// define like this to please codeintel/intellisense IDEs
request.get = verbFunc('get')
request.head = verbFunc('head')
request.post = verbFunc('post')
request.put = verbFunc('put')
request.patch = verbFunc('patch')
request.del = verbFunc('del')
 
request.jar = function (store) {
  return cookies.jar(store)
}
 
request.cookie = function (str) {
  return cookies.parse(str)
}
 
function wrapRequestMethod (method, options, requester, verb) {
 
  return function (uri, opts, callback) {
    var params = initParams(uri, opts, callback)
 
    var headerlessOptions = extend({}, options)
    delete headerlessOptions.headers
    params = extend(headerlessOptions, params)
 
    if (options.headers) {
      var headers = extend({}, options.headers)
      params.headers = extend(headers, params.headers)
    }
 
    if (verb) {
      params.method = (verb === 'del' ? 'DELETE' : verb.toUpperCase())
    }
 
    if (isFunction(requester)) {
      method = requester
    }
 
    return method(params, params.callback)
  }
}
 
request.defaults = function (options, requester) {
  var self = this
 
  if (typeof options === 'function') {
    requester = options
    options = {}
  }
 
  var defaults      = wrapRequestMethod(self, options, requester)
 
  var verbs = ['get', 'head', 'post', 'put', 'patch', 'del']
  verbs.forEach(function(verb) {
    defaults[verb]  = wrapRequestMethod(self[verb], options, requester, verb)
  })
 
  defaults.cookie   = wrapRequestMethod(self.cookie, options, requester)
  defaults.jar      = self.jar
  defaults.defaults = self.defaults
  return defaults
}
 
request.forever = function (agentOptions, optionsArg) {
  var options = {}
  if (optionsArg) {
    options = extend({}, optionsArg)
  }
  if (agentOptions) {
    options.agentOptions = agentOptions
  }
 
  options.forever = true
  return request.defaults(options)
}
 
// Exports
 
module.exports = request
request.Request = require('./request')
request.initParams = initParams
 
// Backwards compatibility for request.debug
Object.defineProperty(request, 'debug', {
  enumerable : true,
  get : function() {
    return request.Request.debug
  },
  set : function(debug) {
    request.Request.debug = debug
  }
})
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/request.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/request.js

Statements: 6.32% (51 / 807)      Branches: 0.16% (1 / 617)      Functions: 0% (0 / 72)      Lines: 6.37% (51 / 801)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558    1                                                     1             1   1                                                   1       1                           1                               1                               1                                 1                                                   1                                                 1           1               1                           1                   1                   1                                                                         1     1 1         1   1                                                             1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     1                                                                                                           1                                                                                                                                                                                                                                                     1                                                                                                                                                 1                                     1                                                                                                                                                                                                                                                                                                                                                                                                                                   1                           1                                                                             1                                                 1                                   1                     1                                                               1                                     1             1                                                                 1                               1       1               1                                                                       1                                     1             1                   1               1               1                 1     1         1 1    
'use strict'
 
var http = require('http')
  , https = require('https')
  , url = require('url')
  , util = require('util')
  , stream = require('stream')
  , zlib = require('zlib')
  , helpers = require('./lib/helpers')
  , bl = require('bl')
  , hawk = require('hawk')
  , aws = require('aws-sign2')
  , httpSignature = require('http-signature')
  , mime = require('mime-types')
  , tunnel = require('tunnel-agent')
  , stringstream = require('stringstream')
  , caseless = require('caseless')
  , ForeverAgent = require('forever-agent')
  , FormData = require('form-data')
  , cookies = require('./lib/cookies')
  , copy = require('./lib/copy')
  , getProxyFromURI = require('./lib/getProxyFromURI')
  , Querystring = require('./lib/querystring').Querystring
  , Har = require('./lib/har').Har
  , Auth = require('./lib/auth').Auth
  , OAuth = require('./lib/oauth').OAuth
  , Multipart = require('./lib/multipart').Multipart
  , Redirect = require('./lib/redirect').Redirect
 
var safeStringify = helpers.safeStringify
  , isReadStream = helpers.isReadStream
  , toBase64 = helpers.toBase64
  , defer = helpers.defer
  , globalCookieJar = cookies.jar()
 
 
var globalPool = {}
 
var defaultProxyHeaderWhiteList = [
  'accept',
  'accept-charset',
  'accept-encoding',
  'accept-language',
  'accept-ranges',
  'cache-control',
  'content-encoding',
  'content-language',
  'content-length',
  'content-location',
  'content-md5',
  'content-range',
  'content-type',
  'connection',
  'date',
  'expect',
  'max-forwards',
  'pragma',
  'referer',
  'te',
  'transfer-encoding',
  'user-agent',
  'via'
]
 
var defaultProxyHeaderExclusiveList = [
  'proxy-authorization'
]
 
function filterForNonReserved(reserved, options) {
  // Filter out properties that are not reserved.
  // Reserved values are passed in at call site.
 
  var object = {}
  for (var i in options) {
    var notReserved = (reserved.indexOf(i) === -1)
    if (notReserved) {
      object[i] = options[i]
    }
  }
  return object
}
 
function filterOutReservedFunctions(reserved, options) {
  // Filter out properties that are functions and are reserved.
  // Reserved values are passed in at call site.
 
  var object = {}
  for (var i in options) {
    var isReserved = !(reserved.indexOf(i) === -1)
    var isFunction = (typeof options[i] === 'function')
    if (!(isReserved && isFunction)) {
      object[i] = options[i]
    }
  }
  return object
 
}
 
function constructProxyHost(uriObject) {
  var port = uriObject.portA
    , protocol = uriObject.protocol
    , proxyHost = uriObject.hostname + ':'
 
  if (port) {
    proxyHost += port
  } else if (protocol === 'https:') {
    proxyHost += '443'
  } else {
    proxyHost += '80'
  }
 
  return proxyHost
}
 
function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) {
  var whiteList = proxyHeaderWhiteList
    .reduce(function (set, header) {
      set[header.toLowerCase()] = true
      return set
    }, {})
 
  return Object.keys(headers)
    .filter(function (header) {
      return whiteList[header.toLowerCase()]
    })
    .reduce(function (set, header) {
      set[header] = headers[header]
      return set
    }, {})
}
 
function getTunnelOption(self, options) {
  // Tunnel HTTPS by default, or if a previous request in the redirect chain
  // was tunneled.  Allow the user to override this setting.
 
  // If self.tunnel is already set (because this is a redirect), use the
  // existing value.
  if (typeof self.tunnel !== 'undefined') {
    return self.tunnel
  }
 
  // If options.tunnel is set (the user specified a value), use it.
  if (typeof options.tunnel !== 'undefined') {
    return options.tunnel
  }
 
  // If the destination is HTTPS, tunnel.
  if (self.uri.protocol === 'https:') {
    return true
  }
 
  // Otherwise, leave tunnel unset, because if a later request in the redirect
  // chain is HTTPS then that request (and any subsequent ones) should be
  // tunneled.
  return undefined
}
 
function constructTunnelOptions(request) {
  var proxy = request.proxy
 
  var tunnelOptions = {
    proxy : {
      host      : proxy.hostname,
      port      : +proxy.port,
      proxyAuth : proxy.auth,
      headers   : request.proxyHeaders
    },
    headers            : request.headers,
    ca                 : request.ca,
    cert               : request.cert,
    key                : request.key,
    passphrase         : request.passphrase,
    pfx                : request.pfx,
    ciphers            : request.ciphers,
    rejectUnauthorized : request.rejectUnauthorized,
    secureOptions      : request.secureOptions,
    secureProtocol     : request.secureProtocol
  }
 
  return tunnelOptions
}
 
function constructTunnelFnName(uri, proxy) {
  var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
  var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
  return [uriProtocol, proxyProtocol].join('Over')
}
 
function getTunnelFn(request) {
  var uri = request.uri
  var proxy = request.proxy
  var tunnelFnName = constructTunnelFnName(uri, proxy)
  return tunnel[tunnelFnName]
}
 
// Function for properly handling a connection error
function connectionErrorHandler(error) {
  var socket = this
  if (socket.res) {
    if (socket.res.request) {
      socket.res.request.emit('error', error)
    } else {
      socket.res.emit('error', error)
    }
  } else {
    socket._httpMessage.emit('error', error)
  }
}
 
// Return a simpler request object to allow serialization
function requestToJSON() {
  var self = this
  return {
    uri: self.uri,
    method: self.method,
    headers: self.headers
  }
}
 
// Return a simpler response object to allow serialization
function responseToJSON() {
  var self = this
  return {
    statusCode: self.statusCode,
    body: self.body,
    headers: self.headers,
    request: requestToJSON.call(self.request)
  }
}
 
function Request (options) {
  // if given the method property in options, set property explicitMethod to true
 
  // extend the Request instance with any non-reserved properties
  // remove any reserved functions from the options object
  // set Request instance to be readable and writable
  // call init
 
  var self = this
 
  // start with HAR, then override with additional options
  if (options.har) {
    self._har = new Har(self)
    options = self._har.options(options)
  }
 
  stream.Stream.call(self)
  var reserved = Object.keys(Request.prototype)
  var nonReserved = filterForNonReserved(reserved, options)
 
  stream.Stream.call(self)
  util._extend(self, nonReserved)
  options = filterOutReservedFunctions(reserved, options)
 
  self.readable = true
  self.writable = true
  if (options.method) {
    self.explicitMethod = true
  }
  self._qs = new Querystring(self)
  self._auth = new Auth(self)
  self._oauth = new OAuth(self)
  self._multipart = new Multipart(self)
  self._redirect = new Redirect(self)
  self.init(options)
}
 
util.inherits(Request, stream.Stream)
 
// Debugging
Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
function debug() {
  if (Request.debug) {
    console.error('REQUEST %s', util.format.apply(util, arguments))
  }
}
Request.prototype.debug = debug
 
Request.prototype.setupTunnel = function () {
  var self = this
 
  if (typeof self.proxy === 'string') {
    self.proxy = url.parse(self.proxy)
  }
 
  if (!self.proxy || !self.tunnel) {
    return false
  }
 
  // Setup Proxy Header Exclusive List and White List
  self.proxyHeaderExclusiveList = self.proxyHeaderExclusiveList || []
  self.proxyHeaderWhiteList = self.proxyHeaderWhiteList || defaultProxyHeaderWhiteList
  var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
  var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
 
  // Setup Proxy Headers and Proxy Headers Host
  // Only send the Proxy White Listed Header names
  self.proxyHeaders = constructProxyHeaderWhiteList(self.headers, proxyHeaderWhiteList)
  self.proxyHeaders.host = constructProxyHost(self.uri)
  proxyHeaderExclusiveList.forEach(self.removeHeader, self)
 
  // Set Agent from Tunnel Data
  var tunnelFn = getTunnelFn(self)
  var tunnelOptions = constructTunnelOptions(self)
  self.agent = tunnelFn(tunnelOptions)
 
  return true
}
 
Request.prototype.init = function (options) {
  // init() contains all the code to setup the request object.
  // the actual outgoing request is not started until start() is called
  // this function is called from both the constructor and on redirect.
  var self = this
  if (!options) {
    options = {}
  }
  self.headers = self.headers ? copy(self.headers) : {}
 
  // Delete headers with value undefined since they break
  // ClientRequest.OutgoingMessage.setHeader in node 0.12
  for (var headerName in self.headers) {
    if (typeof self.headers[headerName] === 'undefined') {
      delete self.headers[headerName]
    }
  }
 
  caseless.httpify(self, self.headers)
 
  if (!self.method) {
    self.method = options.method || 'GET'
  }
  if (!self.localAddress) {
    self.localAddress = options.localAddress
  }
 
  self._qs.init(options)
 
  debug(options)
  if (!self.pool && self.pool !== false) {
    self.pool = globalPool
  }
  self.dests = self.dests || []
  self.__isRequestRequest = true
 
  // Protect against double callback
  if (!self._callback && self.callback) {
    self._callback = self.callback
    self.callback = function () {
      if (self._callbackCalled) {
        return // Print a warning maybe?
      }
      self._callbackCalled = true
      self._callback.apply(self, arguments)
    }
    self.on('error', self.callback.bind())
    self.on('complete', self.callback.bind(self, null))
  }
 
  // People use this property instead all the time, so support it
  if (!self.uri && self.url) {
    self.uri = self.url
    delete self.url
  }
 
  // If there's a baseUrl, then use it as the base URL (i.e. uri must be
  // specified as a relative path and is appended to baseUrl).
  if (self.baseUrl) {
    if (typeof self.baseUrl !== 'string') {
      return self.emit('error', new Error('options.baseUrl must be a string'))
    }
 
    if (typeof self.uri !== 'string') {
      return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
    }
 
    if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
      return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
    }
 
    // Handle all cases to make sure that there's only one slash between
    // baseUrl and uri.
    var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
    var uriStartsWithSlash = self.uri.indexOf('/') === 0
 
    if (baseUrlEndsWithSlash && uriStartsWithSlash) {
      self.uri = self.baseUrl + self.uri.slice(1)
    } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
      self.uri = self.baseUrl + self.uri
    } else if (self.uri === '') {
      self.uri = self.baseUrl
    } else {
      self.uri = self.baseUrl + '/' + self.uri
    }
    delete self.baseUrl
  }
 
  // A URI is needed by this point, emit error if we haven't been able to get one
  if (!self.uri) {
    return self.emit('error', new Error('options.uri is a required argument'))
  }
 
  // If a string URI/URL was given, parse it into a URL object
  if (typeof self.uri === 'string') {
    self.uri = url.parse(self.uri)
  }
 
  // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
  if (self.uri.protocol === 'unix:') {
    return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
  }
 
  // Support Unix Sockets
  if (self.uri.host === 'unix') {
    // Get the socket & request paths from the URL
    var unixParts = self.uri.path.split(':')
      , host = unixParts[0]
      , path = unixParts[1]
    // Apply unix properties to request
    self.socketPath = host
    self.uri.pathname = path
    self.uri.path = path
    self.uri.host = host
    self.uri.hostname = host
    self.uri.isUnix = true
  }
 
  if (self.strictSSL === false) {
    self.rejectUnauthorized = false
  }
 
  if (!self.uri.pathname) {self.uri.pathname = '/'}
 
  if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
    // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
    // Detect and reject it as soon as possible
    var faultyUri = url.format(self.uri)
    var message = 'Invalid URI "' + faultyUri + '"'
    if (Object.keys(options).length === 0) {
      // No option ? This can be the sign of a redirect
      // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
      // they should be warned that it can be caused by a redirection (can save some hair)
      message += '. This can be caused by a crappy redirection.'
    }
    // This error was fatal
    return self.emit('error', new Error(message))
  }
 
  if (!self.hasOwnProperty('proxy')) {
    self.proxy = getProxyFromURI(self.uri)
  }
 
  self.tunnel = getTunnelOption(self, options)
  if (self.proxy) {
    self.setupTunnel()
  }
 
  self._redirect.onRequest(options)
 
  self.setHost = false
  if (!self.hasHeader('host')) {
    var hostHeaderName = self.originalHostHeaderName || 'host'
    self.setHeader(hostHeaderName, self.uri.hostname)
    if (self.uri.port) {
      if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') &&
           !(self.uri.port === 443 && self.uri.protocol === 'https:') ) {
        self.setHeader(hostHeaderName, self.getHeader('host') + (':' + self.uri.port) )
      }
    }
    self.setHost = true
  }
 
  self.jar(self._jar || options.jar)
 
  if (!self.uri.port) {
    if (self.uri.protocol === 'http:') {self.uri.port = 80}
    else if (self.uri.protocol === 'https:') {self.uri.port = 443}
  }
 
  if (self.proxy && !self.tunnel) {
    self.port = self.proxy.port
    self.host = self.proxy.hostname
  } else {
    self.port = self.uri.port
    self.host = self.uri.hostname
  }
 
  if (options.form) {
    self.form(options.form)
  }
 
  if (options.formData) {
    var formData = options.formData
    var requestForm = self.form()
    var appendFormValue = function (key, value) {
      if (value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
        requestForm.append(key, value.value, value.options)
      } else {
        requestForm.append(key, value)
      }
    }
    for (var formKey in formData) {
      if (formData.hasOwnProperty(formKey)) {
        var formValue = formData[formKey]
        if (formValue instanceof Array) {
          for (var j = 0; j < formValue.length; j++) {
            appendFormValue(formKey, formValue[j])
          }
        } else {
          appendFormValue(formKey, formValue)
        }
      }
    }
  }
 
  if (options.qs) {
    self.qs(options.qs)
  }
 
  if (self.uri.path) {
    self.path = self.uri.path
  } else {
    self.path = self.uri.pathname + (self.uri.search || '')
  }
 
  if (self.path.length === 0) {
    self.path = '/'
  }
 
  // Auth must happen last in case signing is dependent on other headers
  if (options.aws) {
    self.aws(options.aws)
  }
 
  if (options.hawk) {
    self.hawk(options.hawk)
  }
 
  if (options.httpSignature) {
    self.httpSignature(options.httpSignature)
  }
 
  if (options.auth) {
    if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
      options.auth.user = options.auth.username
    }
    if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
      options.auth.pass = options.auth.password
    }
 
    self.auth(
      options.auth.user,
      options.auth.pass,
      options.auth.sendImmediately,
      options.auth.bearer
    )
  }
 
  if (self.gzip && !self.hasHeader('accept-encoding')) {
    self.setHeader('accept-encoding', 'gzip')
  }
 
  if (self.uri.auth && !self.hasHeader('authorization')) {
    var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)})
    self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
  }
 
  if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
    var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)})
    var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
    self.setHeader('proxy-authorization', authHeader)
  }
 
  if (self.proxy && !self.tunnel) {
    self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
  }
 
  if (options.json) {
    self.json(options.json)
  }
  if (options.multipart) {
    self.multipart(options.multipart)
  }
 
  if (options.time) {
    self.timing = true
    self.elapsedTime = self.elapsedTime || 0
  }
 
  if (self.body) {
    var length = 0
    if (!Buffer.isBuffer(self.body)) {
      if (Array.isArray(self.body)) {
        for (var i = 0; i < self.body.length; i++) {
          length += self.body[i].length
        }
      } else {
        self.body = new Buffer(self.body)
        length = self.body.length
      }
    } else {
      length = self.body.length
    }
    if (length) {
      if (!self.hasHeader('content-length')) {
        self.setHeader('content-length', length)
      }
    } else {
      self.emit('error', new Error('Argument error, options.body.'))
    }
  }
 
  if (options.oauth) {
    self.oauth(options.oauth)
  } else if (self._oauth.params && self.hasHeader('authorization')) {
    self.oauth(self._oauth.params)
  }
 
  var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
    , defaultModules = {'http:':http, 'https:':https}
    , httpModules = self.httpModules || {}
 
  self.httpModule = httpModules[protocol] || defaultModules[protocol]
 
  if (!self.httpModule) {
    return self.emit('error', new Error('Invalid protocol: ' + protocol))
  }
 
  if (options.ca) {
    self.ca = options.ca
  }
 
  if (!self.agent) {
    if (options.agentOptions) {
      self.agentOptions = options.agentOptions
    }
 
    if (options.agentClass) {
      self.agentClass = options.agentClass
    } else if (options.forever) {
      self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
    } else {
      self.agentClass = self.httpModule.Agent
    }
  }
 
  if (self.pool === false) {
    self.agent = false
  } else {
    self.agent = self.agent || self.getNewAgent()
  }
 
  self.on('pipe', function (src) {
    if (self.ntick && self._started) {
      self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
    }
    self.src = src
    if (isReadStream(src)) {
      if (!self.hasHeader('content-type')) {
        self.setHeader('content-type', mime.lookup(src.path))
      }
    } else {
      if (src.headers) {
        for (var i in src.headers) {
          if (!self.hasHeader(i)) {
            self.setHeader(i, src.headers[i])
          }
        }
      }
      if (self._json && !self.hasHeader('content-type')) {
        self.setHeader('content-type', 'application/json')
      }
      if (src.method && !self.explicitMethod) {
        self.method = src.method
      }
    }
 
    // self.on('pipe', function () {
    //   console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
    // })
  })
 
  defer(function () {
    if (self._aborted) {
      return
    }
 
    var end = function () {
      if (self._form) {
        if (!self._auth.hasAuth) {
          self._form.pipe(self)
        }
        else if (self._auth.hasAuth && self._auth.sentAuth) {
          self._form.pipe(self)
        }
      }
      if (self._multipart && self._multipart.chunked) {
        self._multipart.body.pipe(self)
      }
      if (self.body) {
        if (Array.isArray(self.body)) {
          self.body.forEach(function (part) {
            self.write(part)
          })
        } else {
          self.write(self.body)
        }
        self.end()
      } else if (self.requestBodyStream) {
        console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
        self.requestBodyStream.pipe(self)
      } else if (!self.src) {
        if (self._auth.hasAuth && !self._auth.sentAuth) {
          self.end()
          return
        }
        if (self.method !== 'GET' && typeof self.method !== 'undefined') {
          self.setHeader('content-length', 0)
        }
        self.end()
      }
    }
 
    if (self._form && !self.hasHeader('content-length')) {
      // Before ending the request, we had to compute the length of the whole form, asyncly
      self.setHeader(self._form.getHeaders())
      self._form.getLength(function (err, length) {
        if (!err) {
          self.setHeader('content-length', length)
        }
        end()
      })
    } else {
      end()
    }
 
    self.ntick = true
  })
 
}
 
// Must call this when following a redirect from https to http or vice versa
// Attempts to keep everything as identical as possible, but update the
// httpModule, Tunneling agent, and/or Forever Agent in use.
Request.prototype._updateProtocol = function () {
  var self = this
  var protocol = self.uri.protocol
 
  if (protocol === 'https:' || self.tunnel) {
    // previously was doing http, now doing https
    // if it's https, then we might need to tunnel now.
    if (self.proxy) {
      if (self.setupTunnel()) {
        return
      }
    }
 
    self.httpModule = https
    switch (self.agentClass) {
      case ForeverAgent:
        self.agentClass = ForeverAgent.SSL
        break
      case http.Agent:
        self.agentClass = https.Agent
        break
      default:
        // nothing we can do.  Just hope for the best.
        return
    }
 
    // if there's an agent, we need to get a new one.
    if (self.agent) {
      self.agent = self.getNewAgent()
    }
 
  } else {
    // previously was doing https, now doing http
    self.httpModule = http
    switch (self.agentClass) {
      case ForeverAgent.SSL:
        self.agentClass = ForeverAgent
        break
      case https.Agent:
        self.agentClass = http.Agent
        break
      default:
        // nothing we can do.  just hope for the best
        return
    }
 
    // if there's an agent, then get a new one.
    if (self.agent) {
      self.agent = null
      self.agent = self.getNewAgent()
    }
  }
}
 
Request.prototype.getNewAgent = function () {
  var self = this
  var Agent = self.agentClass
  var options = {}
  if (self.agentOptions) {
    for (var i in self.agentOptions) {
      options[i] = self.agentOptions[i]
    }
  }
  if (self.ca) {
    options.ca = self.ca
  }
  if (self.ciphers) {
    options.ciphers = self.ciphers
  }
  if (self.secureProtocol) {
    options.secureProtocol = self.secureProtocol
  }
  if (self.secureOptions) {
    options.secureOptions = self.secureOptions
  }
  if (typeof self.rejectUnauthorized !== 'undefined') {
    options.rejectUnauthorized = self.rejectUnauthorized
  }
 
  if (self.cert && self.key) {
    options.key = self.key
    options.cert = self.cert
  }
 
  if (self.pfx) {
    options.pfx = self.pfx
  }
 
  if (self.passphrase) {
    options.passphrase = self.passphrase
  }
 
  var poolKey = ''
 
  // different types of agents are in different pools
  if (Agent !== self.httpModule.Agent) {
    poolKey += Agent.name
  }
 
  // ca option is only relevant if proxy or destination are https
  var proxy = self.proxy
  if (typeof proxy === 'string') {
    proxy = url.parse(proxy)
  }
  var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
 
  if (isHttps) {
    if (options.ca) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.ca
    }
 
    if (typeof options.rejectUnauthorized !== 'undefined') {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.rejectUnauthorized
    }
 
    if (options.cert) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
    }
 
    if (options.pfx) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.pfx.toString('ascii')
    }
 
    if (options.ciphers) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.ciphers
    }
 
    if (options.secureProtocol) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.secureProtocol
    }
 
    if (options.secureOptions) {
      if (poolKey) {
        poolKey += ':'
      }
      poolKey += options.secureOptions
    }
  }
 
  if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
    // not doing anything special.  Use the globalAgent
    return self.httpModule.globalAgent
  }
 
  // we're using a stored agent.  Make sure it's protocol-specific
  poolKey = self.uri.protocol + poolKey
 
  // generate a new agent for this setting if none yet exists
  if (!self.pool[poolKey]) {
    self.pool[poolKey] = new Agent(options)
    // properly set maxSockets on new agents
    if (self.pool.maxSockets) {
      self.pool[poolKey].maxSockets = self.pool.maxSockets
    }
  }
 
  return self.pool[poolKey]
}
 
Request.prototype.start = function () {
  // start() is called once we are ready to send the outgoing HTTP request.
  // this is usually called on the first write(), end() or on nextTick()
  var self = this
 
  if (self._aborted) {
    return
  }
 
  self._started = true
  self.method = self.method || 'GET'
  self.href = self.uri.href
 
  if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
    self.setHeader('content-length', self.src.stat.size)
  }
  if (self._aws) {
    self.aws(self._aws, true)
  }
 
  // We have a method named auth, which is completely different from the http.request
  // auth option.  If we don't remove it, we're gonna have a bad time.
  var reqOptions = copy(self)
  delete reqOptions.auth
 
  debug('make request', self.uri.href)
 
  self.req = self.httpModule.request(reqOptions)
 
  if (self.timing) {
    self.startTime = new Date().getTime()
  }
 
  if (self.timeout && !self.timeoutTimer) {
    var timeout = self.timeout < 0 ? 0 : self.timeout
    self.timeoutTimer = setTimeout(function () {
      self.abort()
      var e = new Error('ETIMEDOUT')
      e.code = 'ETIMEDOUT'
      self.emit('error', e)
    }, timeout)
 
    // Set additional timeout on socket - in case if remote
    // server freeze after sending headers
    if (self.req.setTimeout) { // only works on node 0.6+
      self.req.setTimeout(timeout, function () {
        if (self.req) {
          self.req.abort()
          var e = new Error('ESOCKETTIMEDOUT')
          e.code = 'ESOCKETTIMEDOUT'
          self.emit('error', e)
        }
      })
    }
  }
 
  self.req.on('response', self.onRequestResponse.bind(self))
  self.req.on('error', self.onRequestError.bind(self))
  self.req.on('drain', function() {
    self.emit('drain')
  })
  self.req.on('socket', function(socket) {
    self.emit('socket', socket)
  })
 
  self.on('end', function() {
    if ( self.req.connection ) {
      self.req.connection.removeListener('error', connectionErrorHandler)
    }
  })
  self.emit('request', self.req)
}
 
Request.prototype.onRequestError = function (error) {
  var self = this
  if (self._aborted) {
    return
  }
  if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET'
      && self.agent.addRequestNoreuse) {
    self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
    self.start()
    self.req.end()
    return
  }
  if (self.timeout && self.timeoutTimer) {
    clearTimeout(self.timeoutTimer)
    self.timeoutTimer = null
  }
  self.emit('error', error)
}
 
Request.prototype.onRequestResponse = function (response) {
  var self = this
  debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
  response.on('end', function() {
    if (self.timing) {
      self.elapsedTime += (new Date().getTime() - self.startTime)
      debug('elapsed time', self.elapsedTime)
      response.elapsedTime = self.elapsedTime
    }
    debug('response end', self.uri.href, response.statusCode, response.headers)
  })
 
  // The check on response.connection is a workaround for browserify.
  if (response.connection && response.connection.listeners('error').indexOf(connectionErrorHandler) === -1) {
    response.connection.setMaxListeners(0)
    response.connection.once('error', connectionErrorHandler)
  }
  if (self._aborted) {
    debug('aborted', self.uri.href)
    response.resume()
    return
  }
 
  self.response = response
  response.request = self
  response.toJSON = responseToJSON
 
  // XXX This is different on 0.10, because SSL is strict by default
  if (self.httpModule === https &&
      self.strictSSL && (!response.hasOwnProperty('client') ||
      !response.client.authorized)) {
    debug('strict ssl error', self.uri.href)
    var sslErr = response.hasOwnProperty('client') ? response.client.authorizationError : self.uri.href + ' does not support SSL'
    self.emit('error', new Error('SSL Error: ' + sslErr))
    return
  }
 
  // Save the original host before any redirect (if it changes, we need to
  // remove any authorization headers).  Also remember the case of the header
  // name because lots of broken servers expect Host instead of host and we
  // want the caller to be able to specify this.
  self.originalHost = self.getHeader('host')
  if (!self.originalHostHeaderName) {
    self.originalHostHeaderName = self.hasHeader('host')
  }
  if (self.setHost) {
    self.removeHeader('host')
  }
  if (self.timeout && self.timeoutTimer) {
    clearTimeout(self.timeoutTimer)
    self.timeoutTimer = null
  }
 
  var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
  var addCookie = function (cookie) {
    //set the cookie if it's domain in the href's domain.
    try {
      targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
    } catch (e) {
      self.emit('error', e)
    }
  }
 
  response.caseless = caseless(response.headers)
 
  if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
    var headerName = response.caseless.has('set-cookie')
    if (Array.isArray(response.headers[headerName])) {
      response.headers[headerName].forEach(addCookie)
    } else {
      addCookie(response.headers[headerName])
    }
  }
 
  if (self._redirect.onResponse(response)) {
    return // Ignore the rest of the response
  } else {
    // Be a good stream and emit end when the response is finished.
    // Hack to emit end on close because of a core bug that never fires end
    response.on('close', function () {
      if (!self._ended) {
        self.response.emit('end')
      }
    })
 
    response.on('end', function () {
      self._ended = true
    })
 
    var responseContent
    if (self.gzip) {
      var contentEncoding = response.headers['content-encoding'] || 'identity'
      contentEncoding = contentEncoding.trim().toLowerCase()
 
      if (contentEncoding === 'gzip') {
        responseContent = zlib.createGunzip()
        response.pipe(responseContent)
      } else {
        // Since previous versions didn't check for Content-Encoding header,
        // ignore any invalid values to preserve backwards-compatibility
        if (contentEncoding !== 'identity') {
          debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
        }
        responseContent = response
      }
    } else {
      responseContent = response
    }
 
    if (self.encoding) {
      if (self.dests.length !== 0) {
        console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
      } else if (responseContent.setEncoding) {
        responseContent.setEncoding(self.encoding)
      } else {
        // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with
        // zlib streams.
        // If/When support for 0.9.4 is dropped, this should be unnecessary.
        responseContent = responseContent.pipe(stringstream(self.encoding))
      }
    }
 
    if (self._paused) {
      responseContent.pause()
    }
 
    self.responseContent = responseContent
 
    self.emit('response', response)
 
    self.dests.forEach(function (dest) {
      self.pipeDest(dest)
    })
 
    responseContent.on('data', function (chunk) {
      self._destdata = true
      self.emit('data', chunk)
    })
    responseContent.on('end', function (chunk) {
      self.emit('end', chunk)
    })
    responseContent.on('error', function (error) {
      self.emit('error', error)
    })
    responseContent.on('close', function () {self.emit('close')})
 
    if (self.callback) {
      var buffer = bl()
        , strings = []
 
      self.on('data', function (chunk) {
        if (Buffer.isBuffer(chunk)) {
          buffer.append(chunk)
        } else {
          strings.push(chunk)
        }
      })
      self.on('end', function () {
        debug('end event', self.uri.href)
        if (self._aborted) {
          debug('aborted', self.uri.href)
          return
        }
 
        if (buffer.length) {
          debug('has body', self.uri.href, buffer.length)
          if (self.encoding === null) {
            // response.body = buffer
            // can't move to this until https://github.com/rvagg/bl/issues/13
            response.body = buffer.slice()
          } else {
            response.body = buffer.toString(self.encoding)
          }
        } else if (strings.length) {
          // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
          // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
          if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
            strings[0] = strings[0].substring(1)
          }
          response.body = strings.join('')
        }
 
        if (self._json) {
          try {
            response.body = JSON.parse(response.body, self._jsonReviver)
          } catch (e) {
            // empty
          }
        }
        debug('emitting complete', self.uri.href)
        if (typeof response.body === 'undefined' && !self._json) {
          response.body = self.encoding === null ? new Buffer(0) : ''
        }
        self.emit('complete', response, response.body)
      })
    }
    //if no callback
    else {
      self.on('end', function () {
        if (self._aborted) {
          debug('aborted', self.uri.href)
          return
        }
        self.emit('complete', response)
      })
    }
  }
  debug('finish init function', self.uri.href)
}
 
Request.prototype.abort = function () {
  var self = this
  self._aborted = true
 
  if (self.req) {
    self.req.abort()
  }
  else if (self.response) {
    self.response.abort()
  }
 
  self.emit('abort')
}
 
Request.prototype.pipeDest = function (dest) {
  var self = this
  var response = self.response
  // Called after the response is received
  if (dest.headers && !dest.headersSent) {
    if (response.caseless.has('content-type')) {
      var ctname = response.caseless.has('content-type')
      if (dest.setHeader) {
        dest.setHeader(ctname, response.headers[ctname])
      }
      else {
        dest.headers[ctname] = response.headers[ctname]
      }
    }
 
    if (response.caseless.has('content-length')) {
      var clname = response.caseless.has('content-length')
      if (dest.setHeader) {
        dest.setHeader(clname, response.headers[clname])
      } else {
        dest.headers[clname] = response.headers[clname]
      }
    }
  }
  if (dest.setHeader && !dest.headersSent) {
    for (var i in response.headers) {
      // If the response content is being decoded, the Content-Encoding header
      // of the response doesn't represent the piped content, so don't pass it.
      if (!self.gzip || i !== 'content-encoding') {
        dest.setHeader(i, response.headers[i])
      }
    }
    dest.statusCode = response.statusCode
  }
  if (self.pipefilter) {
    self.pipefilter(response, dest)
  }
}
 
Request.prototype.qs = function (q, clobber) {
  var self = this
  var base
  if (!clobber && self.uri.query) {
    base = self._qs.parse(self.uri.query)
  } else {
    base = {}
  }
 
  for (var i in q) {
    base[i] = q[i]
  }
 
  if (self._qs.stringify(base) === '') {
    return self
  }
 
  var qs = self._qs.stringify(base)
 
  self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
  self.url = self.uri
  self.path = self.uri.path
 
  return self
}
Request.prototype.form = function (form) {
  var self = this
  if (form) {
    self.setHeader('content-type', 'application/x-www-form-urlencoded')
    self.body = (typeof form === 'string')
      ? self._qs.rfc3986(form.toString('utf8'))
      : self._qs.stringify(form).toString('utf8')
    return self
  }
  // create form-data object
  self._form = new FormData()
  self._form.on('error', function(err) {
    err.message = 'form-data: ' + err.message
    self.emit('error', err)
    self.abort()
  })
  return self._form
}
Request.prototype.multipart = function (multipart) {
  var self = this
 
  self._multipart.onRequest(multipart)
 
  if (!self._multipart.chunked) {
    self.body = self._multipart.body
  }
 
  return self
}
Request.prototype.json = function (val) {
  var self = this
 
  if (!self.hasHeader('accept')) {
    self.setHeader('accept', 'application/json')
  }
 
  self._json = true
  if (typeof val === 'boolean') {
    if (self.body !== undefined) {
      if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
        self.body = safeStringify(self.body)
      } else {
        self.body = self._qs.rfc3986(self.body)
      }
      if (!self.hasHeader('content-type')) {
        self.setHeader('content-type', 'application/json')
      }
    }
  } else {
    self.body = safeStringify(val)
    if (!self.hasHeader('content-type')) {
      self.setHeader('content-type', 'application/json')
    }
  }
 
  if (typeof self.jsonReviver === 'function') {
    self._jsonReviver = self.jsonReviver
  }
 
  return self
}
Request.prototype.getHeader = function (name, headers) {
  var self = this
  var result, re, match
  if (!headers) {
    headers = self.headers
  }
  Object.keys(headers).forEach(function (key) {
    if (key.length !== name.length) {
      return
    }
    re = new RegExp(name, 'i')
    match = key.match(re)
    if (match) {
      result = headers[key]
    }
  })
  return result
}
 
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
  var self = this
 
  self._auth.onRequest(user, pass, sendImmediately, bearer)
 
  return self
}
Request.prototype.aws = function (opts, now) {
  var self = this
 
  if (!now) {
    self._aws = opts
    return self
  }
  var date = new Date()
  self.setHeader('date', date.toUTCString())
  var auth =
    { key: opts.key
    , secret: opts.secret
    , verb: self.method.toUpperCase()
    , date: date
    , contentType: self.getHeader('content-type') || ''
    , md5: self.getHeader('content-md5') || ''
    , amazonHeaders: aws.canonicalizeHeaders(self.headers)
    }
  var path = self.uri.path
  if (opts.bucket && path) {
    auth.resource = '/' + opts.bucket + path
  } else if (opts.bucket && !path) {
    auth.resource = '/' + opts.bucket
  } else if (!opts.bucket && path) {
    auth.resource = path
  } else if (!opts.bucket && !path) {
    auth.resource = '/'
  }
  auth.resource = aws.canonicalizeResource(auth.resource)
  self.setHeader('authorization', aws.authorization(auth))
 
  return self
}
Request.prototype.httpSignature = function (opts) {
  var self = this
  httpSignature.signRequest({
    getHeader: function(header) {
      return self.getHeader(header, self.headers)
    },
    setHeader: function(header, value) {
      self.setHeader(header, value)
    },
    method: self.method,
    path: self.path
  }, opts)
  debug('httpSignature authorization', self.getHeader('authorization'))
 
  return self
}
Request.prototype.hawk = function (opts) {
  var self = this
  self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field)
}
Request.prototype.oauth = function (_oauth) {
  var self = this
 
  self._oauth.onRequest(_oauth)
 
  return self
}
 
Request.prototype.jar = function (jar) {
  var self = this
  var cookies
 
  if (self._redirect.redirectsFollowed === 0) {
    self.originalCookieHeader = self.getHeader('cookie')
  }
 
  if (!jar) {
    // disable cookies
    cookies = false
    self._disableCookies = true
  } else {
    var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
    var urihref = self.uri.href
    //fetch cookie in the Specified host
    if (targetCookieJar) {
      cookies = targetCookieJar.getCookieString(urihref)
    }
  }
 
  //if need cookie and cookie is not empty
  if (cookies && cookies.length) {
    if (self.originalCookieHeader) {
      // Don't overwrite existing Cookie header
      self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
    } else {
      self.setHeader('cookie', cookies)
    }
  }
  self._jar = jar
  return self
}
 
 
// Stream API
Request.prototype.pipe = function (dest, opts) {
  var self = this
 
  if (self.response) {
    if (self._destdata) {
      self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
    } else if (self._ended) {
      self.emit('error', new Error('You cannot pipe after the response has been ended.'))
    } else {
      stream.Stream.prototype.pipe.call(self, dest, opts)
      self.pipeDest(dest)
      return dest
    }
  } else {
    self.dests.push(dest)
    stream.Stream.prototype.pipe.call(self, dest, opts)
    return dest
  }
}
Request.prototype.write = function () {
  var self = this
  if (!self._started) {
    self.start()
  }
  return self.req.write.apply(self.req, arguments)
}
Request.prototype.end = function (chunk) {
  var self = this
  if (chunk) {
    self.write(chunk)
  }
  if (!self._started) {
    self.start()
  }
  self.req.end()
}
Request.prototype.pause = function () {
  var self = this
  if (!self.responseContent) {
    self._paused = true
  } else {
    self.responseContent.pause.apply(self.responseContent, arguments)
  }
}
Request.prototype.resume = function () {
  var self = this
  if (!self.responseContent) {
    self._paused = false
  } else {
    self.responseContent.resume.apply(self.responseContent, arguments)
  }
}
Request.prototype.destroy = function () {
  var self = this
  if (!self._ended) {
    self.end()
  } else if (self.response) {
    self.response.destroy()
  }
}
 
Request.defaultProxyHeaderWhiteList =
  defaultProxyHeaderWhiteList.slice()
 
Request.defaultProxyHeaderExclusiveList =
  defaultProxyHeaderExclusiveList.slice()
 
// Exports
 
Request.prototype.toJSON = requestToJSON
module.exports = Request
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/

Statements: 16.6% (82 / 494)      Branches: 0.27% (1 / 365)      Functions: 5% (3 / 60)      Lines: 16.73% (82 / 490)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/lib/
File Statements Branches Functions Lines
auth.js 11.39% (9 / 79) 0% (0 / 55) 0% (0 / 6) 11.54% (9 / 78)
cookies.js 50% (11 / 22) 0% (0 / 8) 33.33% (2 / 6) 50% (11 / 22)
copy.js 20% (1 / 5) 100% (0 / 0) 0% (0 / 2) 20% (1 / 5)
getProxyFromURI.js 20% (5 / 25) 0% (0 / 31) 0% (0 / 5) 20% (5 / 25)
har.js 9.28% (9 / 97) 0% (0 / 85) 0% (0 / 7) 9.28% (9 / 97)
helpers.js 60.71% (17 / 28) 8.33% (1 / 12) 14.29% (1 / 7) 60.71% (17 / 28)
multipart.js 13.56% (8 / 59) 0% (0 / 36) 0% (0 / 9) 13.79% (8 / 58)
oauth.js 10% (7 / 70) 0% (0 / 57) 0% (0 / 7) 10% (7 / 70)
querystring.js 34.78% (8 / 23) 0% (0 / 20) 0% (0 / 6) 36.36% (8 / 22)
redirect.js 8.14% (7 / 86) 0% (0 / 61) 0% (0 / 5) 8.24% (7 / 85)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/auth.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/auth.js

Statements: 11.39% (9 / 79)      Branches: 0% (0 / 55)      Functions: 0% (0 / 6)      Lines: 11.54% (9 / 78)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155    1       1       1                   1                               1                           1                                                                                                                         1                                 1                                               1    
'use strict'
 
var caseless = require('caseless')
  , uuid = require('node-uuid')
  , helpers = require('./helpers')
 
var md5 = helpers.md5
  , toBase64 = helpers.toBase64
 
 
function Auth (request) {
  // define all public properties here
  this.request = request
  this.hasAuth = false
  this.sentAuth = false
  this.bearerToken = null
  this.user = null
  this.pass = null
}
 
Auth.prototype.basic = function (user, pass, sendImmediately) {
  var self = this
  if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
    self.request.emit('error', new Error('auth() received invalid user or password'))
  }
  self.user = user
  self.pass = pass
  self.hasAuth = true
  var header = user + ':' + (pass || '')
  if (sendImmediately || typeof sendImmediately === 'undefined') {
    var authHeader = 'Basic ' + toBase64(header)
    self.sentAuth = true
    return authHeader
  }
}
 
Auth.prototype.bearer = function (bearer, sendImmediately) {
  var self = this
  self.bearerToken = bearer
  self.hasAuth = true
  if (sendImmediately || typeof sendImmediately === 'undefined') {
    if (typeof bearer === 'function') {
      bearer = bearer()
    }
    var authHeader = 'Bearer ' + (bearer || '')
    self.sentAuth = true
    return authHeader
  }
}
 
Auth.prototype.digest = function (method, path, authHeader) {
  // TODO: More complete implementation of RFC 2617.
  //   - check challenge.algorithm
  //   - support algorithm="MD5-sess"
  //   - handle challenge.domain
  //   - support qop="auth-int" only
  //   - handle Authentication-Info (not necessarily?)
  //   - check challenge.stale (not necessarily?)
  //   - increase nc (not necessarily?)
  // For reference:
  // http://tools.ietf.org/html/rfc2617#section-3
  // https://github.com/bagder/curl/blob/master/lib/http_digest.c
 
  var self = this
 
  var challenge = {}
  var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
  for (;;) {
    var match = re.exec(authHeader)
    if (!match) {
      break
    }
    challenge[match[1]] = match[2] || match[3]
  }
 
  var ha1 = md5(self.user + ':' + challenge.realm + ':' + self.pass)
  var ha2 = md5(method + ':' + path)
  var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
  var nc = qop && '00000001'
  var cnonce = qop && uuid().replace(/-/g, '')
  var digestResponse = qop
    ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
    : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
  var authValues = {
    username: self.user,
    realm: challenge.realm,
    nonce: challenge.nonce,
    uri: path,
    qop: qop,
    response: digestResponse,
    nc: nc,
    cnonce: cnonce,
    algorithm: challenge.algorithm,
    opaque: challenge.opaque
  }
 
  authHeader = []
  for (var k in authValues) {
    if (authValues[k]) {
      if (k === 'qop' || k === 'nc' || k === 'algorithm') {
        authHeader.push(k + '=' + authValues[k])
      } else {
        authHeader.push(k + '="' + authValues[k] + '"')
      }
    }
  }
  authHeader = 'Digest ' + authHeader.join(', ')
  self.sentAuth = true
  return authHeader
}
 
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
  var self = this
    , request = self.request
 
  var authHeader
  if (bearer === undefined && user === undefined) {
    self.request.emit('error', new Error('no auth mechanism defined'))
  } else if (bearer !== undefined) {
    authHeader = self.bearer(bearer, sendImmediately)
  } else {
    authHeader = self.basic(user, pass, sendImmediately)
  }
  if (authHeader) {
    request.setHeader('authorization', authHeader)
  }
}
 
Auth.prototype.onResponse = function (response) {
  var self = this
    , request = self.request
 
  if (!self.hasAuth || self.sentAuth) { return null }
 
  var c = caseless(response.headers)
 
  var authHeader = c.get('www-authenticate')
  var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
  request.debug('reauth', authVerb)
 
  switch (authVerb) {
    case 'basic':
      return self.basic(self.user, self.pass, true)
 
    case 'bearer':
      return self.bearer(self.bearerToken, true)
 
    case 'digest':
      return self.digest(request.method, request.path, authHeader)
  }
}
 
exports.Auth = Auth
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/cookies.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/cookies.js

Statements: 50% (11 / 22)      Branches: 0% (0 / 8)      Functions: 33.33% (2 / 6)      Lines: 50% (11 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41    1   1       1                     1 1 1   1       1       1         1 1      
'use strict'
 
var tough = require('tough-cookie')
 
var Cookie = tough.Cookie
  , CookieJar = tough.CookieJar
 
 
exports.parse = function(str) {
  if (str && str.uri) {
    str = str.uri
  }
  if (typeof str !== 'string') {
    throw new Error('The cookie function only accepts STRING as param')
  }
  return Cookie.parse(str)
}
 
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
function RequestJar(store) {
  var self = this
  self._jar = new CookieJar(store)
}
RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
  var self = this
  return self._jar.setCookieSync(cookieOrStr, uri, options || {})
}
RequestJar.prototype.getCookieString = function(uri) {
  var self = this
  return self._jar.getCookieStringSync(uri)
}
RequestJar.prototype.getCookies = function(uri) {
  var self = this
  return self._jar.getCookiesSync(uri)
}
 
exports.jar = function(store) {
  return new RequestJar(store)
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/copy.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/copy.js

Statements: 20% (1 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 2)      Lines: 20% (1 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12    1                  
'use strict'
 
module.exports =
function copy (obj) {
  var o = {}
  Object.keys(obj).forEach(function (i) {
    o[i] = obj[i]
  })
  return o
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/getProxyFromURI.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/getProxyFromURI.js

Statements: 20% (5 / 25)      Branches: 0% (0 / 31)      Functions: 0% (0 / 5)      Lines: 20% (5 / 25)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81    1         1                     1                                         1                                                                             1    
'use strict'
 
function formatHostname(hostname) {
  // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
  return hostname.replace(/^\.*/, '.').toLowerCase()
}
 
function parseNoProxyZone(zone) {
  zone = zone.trim().toLowerCase()
 
  var zoneParts = zone.split(':', 2)
    , zoneHost = formatHostname(zoneParts[0])
    , zonePort = zoneParts[1]
    , hasPort = zone.indexOf(':') > -1
 
  return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
}
 
function uriInNoProxy(uri, noProxy) {
  var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
    , hostname = formatHostname(uri.hostname)
    , noProxyList = noProxy.split(',')
 
  // iterate through the noProxyList until it finds a match.
  return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
    var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
      , hostnameMatched = (
          isMatchedAt > -1 &&
          (isMatchedAt === hostname.length - noProxyZone.hostname.length)
        )
 
    if (noProxyZone.hasPort) {
      return (port === noProxyZone.port) && hostnameMatched
    }
 
    return hostnameMatched
  })
}
 
function getProxyFromURI(uri) {
  // Decide the proper request proxy to use based on the request URI object and the
  // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
  // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
 
  var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
 
  // if the noProxy is a wildcard then return null
 
  if (noProxy === '*') {
    return null
  }
 
  // if the noProxy is not empty and the uri is found return null
 
  if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
    return null
  }
 
  // Check for HTTP or HTTPS Proxy in environment Else default to null
 
  if (uri.protocol === 'http:') {
    return process.env.HTTP_PROXY ||
           process.env.http_proxy || null
  }
 
  if (uri.protocol === 'https:') {
    return process.env.HTTPS_PROXY ||
           process.env.https_proxy ||
           process.env.HTTP_PROXY  ||
           process.env.http_proxy  || null
  }
 
  // if none of that works, return null
  // (What uri protocol are you using then?)
 
  return null
}
 
module.exports = getProxyFromURI
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/har.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/har.js

Statements: 9.28% (9 / 97)      Branches: 0% (0 / 85)      Functions: 0% (0 / 7)      Lines: 9.28% (9 / 97)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207    1 1 1 1   1       1                                   1                                                                                                                                                     1                                                                                                                                                                                                       1    
'use strict'
 
var fs = require('fs')
var qs = require('querystring')
var validate = require('har-validator')
var util = require('util')
 
function Har (request) {
  this.request = request
}
 
Har.prototype.reducer = function (obj, pair) {
  // new property ?
  if (obj[pair.name] === undefined) {
    obj[pair.name] = pair.value
    return obj
  }
 
  // existing? convert to array
  var arr = [
    obj[pair.name],
    pair.value
  ]
 
  obj[pair.name] = arr
 
  return obj
}
 
Har.prototype.prep = function (data) {
  // construct utility properties
  data.queryObj = {}
  data.headersObj = {}
  data.postData.jsonObj = false
  data.postData.paramsObj = false
 
  // construct query objects
  if (data.queryString && data.queryString.length) {
    data.queryObj = data.queryString.reduce(this.reducer, {})
  }
 
  // construct headers objects
  if (data.headers && data.headers.length) {
    // loweCase header keys
    data.headersObj = data.headers.reduceRight(function (headers, header) {
      headers[header.name] = header.value
      return headers
    }, {})
  }
 
  // construct Cookie header
  if (data.cookies && data.cookies.length) {
    var cookies = data.cookies.map(function (cookie) {
      return cookie.name + '=' + cookie.value
    })
 
    if (cookies.length) {
      data.headersObj.cookie = cookies.join('; ')
    }
  }
 
  // prep body
  switch (data.postData.mimeType) {
    case 'multipart/mixed':
    case 'multipart/related':
    case 'multipart/form-data':
    case 'multipart/alternative':
      // reset values
      data.postData.mimeType = 'multipart/form-data'
      break
 
    case 'application/x-www-form-urlencoded':
      if (!data.postData.params) {
        data.postData.text = ''
      } else {
        data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
 
        // always overwrite
        data.postData.text = qs.stringify(data.postData.paramsObj)
      }
      break
 
    case 'text/json':
    case 'text/x-json':
    case 'application/json':
    case 'application/x-json':
      data.postData.mimeType = 'application/json'
 
      if (data.postData.text) {
        try {
          data.postData.jsonObj = JSON.parse(data.postData.text)
        } catch (e) {
          this.request.debug(e)
 
          // force back to text/plain
          data.postData.mimeType = 'text/plain'
        }
      }
      break
  }
 
  return data
}
 
Har.prototype.options = function (options) {
  // skip if no har property defined
  if (!options.har) {
    return options
  }
 
  var har = util._extend({}, options.har)
 
  // only process the first entry
  if (har.log && har.log.entries) {
    har = har.log.entries[0]
  }
 
  // add optional properties to make validation successful
  har.url = har.url || options.url || options.uri || options.baseUrl || '/'
  har.httpVersion = har.httpVersion || 'HTTP/1.1'
  har.queryString = har.queryString || []
  har.headers = har.headers || []
  har.cookies = har.cookies || []
  har.postData = har.postData || {}
  har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
 
  har.bodySize = 0
  har.headersSize = 0
  har.postData.size = 0
 
  if (!validate.request(har)) {
    return options
  }
 
  // clean up and get some utility properties
  var req = this.prep(har)
 
  // construct new options
  if (req.url) {
    options.url = req.url
  }
 
  if (req.method) {
    options.method = req.method
  }
 
  if (Object.keys(req.queryObj).length) {
    options.qs = req.queryObj
  }
 
  if (Object.keys(req.headersObj).length) {
    options.headers = req.headersObj
  }
 
  switch (req.postData.mimeType) {
    case 'application/x-www-form-urlencoded':
      options.form = req.postData.paramsObj
      break
 
    case 'application/json':
      if (req.postData.jsonObj) {
        options.body = req.postData.jsonObj
        options.json = true
      }
      break
 
    case 'multipart/form-data':
      options.formData = {}
 
      req.postData.params.forEach(function (param) {
        var attachment = {}
 
        if (!param.fileName && !param.fileName && !param.contentType) {
          options.formData[param.name] = param.value
          return
        }
 
        // attempt to read from disk!
        if (param.fileName && !param.value) {
          attachment.value = fs.createReadStream(param.fileName)
        } else if (param.value) {
          attachment.value = param.value
        }
 
        if (param.fileName) {
          attachment.options = {
            filename: param.fileName,
            contentType: param.contentType ? param.contentType : null
          }
        }
 
        options.formData[param.name] = attachment
      })
      break
 
    default:
      if (req.postData.text) {
        options.body = req.postData.text
      }
  }
 
  return options
}
 
exports.Har = Har
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/helpers.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/helpers.js

Statements: 60.71% (17 / 28)      Branches: 8.33% (1 / 12)      Functions: 14.29% (1 / 7)      Lines: 60.71% (17 / 28)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57    1     1 1       1     1       1                 1                   1       1       1       1 1 1 1 1 1 1    
'use strict'
 
var jsonSafeStringify = require('json-stringify-safe')
  , crypto = require('crypto')
 
function deferMethod() {
  Iif (typeof setImmediate === 'undefined') {
    return process.nextTick
  }
 
  return setImmediate
}
 
function isFunction(value) {
  return typeof value === 'function'
}
 
function paramsHaveRequestBody(params) {
  return (
    params.body ||
    params.requestBodyStream ||
    (params.json && typeof params.json !== 'boolean') ||
    params.multipart
  )
}
 
function safeStringify (obj) {
  var ret
  try {
    ret = JSON.stringify(obj)
  } catch (e) {
    ret = jsonSafeStringify(obj)
  }
  return ret
}
 
function md5 (str) {
  return crypto.createHash('md5').update(str).digest('hex')
}
 
function isReadStream (rs) {
  return rs.readable && rs.path && rs.mode
}
 
function toBase64 (str) {
  return (new Buffer(str || '', 'utf8')).toString('base64')
}
 
exports.isFunction            = isFunction
exports.paramsHaveRequestBody = paramsHaveRequestBody
exports.safeStringify         = safeStringify
exports.md5                   = md5
exports.isReadStream          = isReadStream
exports.toBase64              = toBase64
exports.defer                 = deferMethod()
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/multipart.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/multipart.js

Statements: 13.56% (8 / 59)      Branches: 0% (0 / 36)      Functions: 0% (0 / 9)      Lines: 13.79% (8 / 58)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111    1         1             1                                                             1                                       1       1                                                       1                     1    
'use strict'
 
var uuid = require('node-uuid')
  , CombinedStream = require('combined-stream')
  , isstream = require('isstream')
 
 
function Multipart (request) {
  this.request = request
  this.boundary = uuid()
  this.chunked = false
  this.body = null
}
 
Multipart.prototype.isChunked = function (options) {
  var self = this
    , chunked = false
    , parts = options.data || options
 
  if (!parts.forEach) {
    self.request.emit('error', new Error('Argument error, options.multipart.'))
  }
 
  if (options.chunked !== undefined) {
    chunked = options.chunked
  }
 
  if (self.request.getHeader('transfer-encoding') === 'chunked') {
    chunked = true
  }
 
  if (!chunked) {
    parts.forEach(function (part) {
      if (typeof part.body === 'undefined') {
        self.request.emit('error', new Error('Body attribute missing in multipart.'))
      }
      if (isstream(part.body)) {
        chunked = true
      }
    })
  }
 
  return chunked
}
 
Multipart.prototype.setHeaders = function (chunked) {
  var self = this
 
  if (chunked && !self.request.hasHeader('transfer-encoding')) {
    self.request.setHeader('transfer-encoding', 'chunked')
  }
 
  var header = self.request.getHeader('content-type')
 
  if (!header || header.indexOf('multipart') === -1) {
    self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
  } else {
    if (header.indexOf('boundary') !== -1) {
      self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
    } else {
      self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
    }
  }
}
 
Multipart.prototype.build = function (parts, chunked) {
  var self = this
  var body = chunked ? new CombinedStream() : []
 
  function add (part) {
    return chunked ? body.append(part) : body.push(new Buffer(part))
  }
 
  if (self.request.preambleCRLF) {
    add('\r\n')
  }
 
  parts.forEach(function (part) {
    var preamble = '--' + self.boundary + '\r\n'
    Object.keys(part).forEach(function (key) {
      if (key === 'body') { return }
      preamble += key + ': ' + part[key] + '\r\n'
    })
    preamble += '\r\n'
    add(preamble)
    add(part.body)
    add('\r\n')
  })
  add('--' + self.boundary + '--')
 
  if (self.request.postambleCRLF) {
    add('\r\n')
  }
 
  return body
}
 
Multipart.prototype.onRequest = function (options) {
  var self = this
 
  var chunked = self.isChunked(options)
    , parts = options.data || options
 
  self.setHeaders(chunked)
  self.chunked = chunked
  self.body = self.build(parts, chunked)
}
 
exports.Multipart = Multipart
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/oauth.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/oauth.js

Statements: 10% (7 / 70)      Branches: 0% (0 / 57)      Functions: 0% (0 / 7)      Lines: 10% (7 / 70)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146    1             1         1                                                                                             1                         1                                 1                                                                                                       1    
'use strict'
 
var qs = require('qs')
  , caseless = require('caseless')
  , uuid = require('node-uuid')
  , oauth = require('oauth-sign')
  , crypto = require('crypto')
 
 
function OAuth (request) {
  this.request = request
  this.params = null
}
 
OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
  var oa = {}
  for (var i in _oauth) {
    oa['oauth_' + i] = _oauth[i]
  }
  if (!oa.oauth_version) {
    oa.oauth_version = '1.0'
  }
  if (!oa.oauth_timestamp) {
    oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
  }
  if (!oa.oauth_nonce) {
    oa.oauth_nonce = uuid().replace(/-/g, '')
  }
  if (!oa.oauth_signature_method) {
    oa.oauth_signature_method = 'HMAC-SHA1'
  }
 
  var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
  delete oa.oauth_consumer_secret
  delete oa.oauth_private_key
 
  var token_secret = oa.oauth_token_secret
  delete oa.oauth_token_secret
 
  var realm = oa.oauth_realm
  delete oa.oauth_realm
  delete oa.oauth_transport_method
 
  var baseurl = uri.protocol + '//' + uri.host + uri.pathname
  var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
 
  oa.oauth_signature = oauth.sign(
    oa.oauth_signature_method,
    method,
    baseurl,
    params,
    consumer_secret_or_private_key,
    token_secret)
 
  if (realm) {
    oa.realm = realm
  }
 
  return oa
}
 
OAuth.prototype.buildBodyHash = function(_oauth, body) {
  if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
    this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
      ' signature_method not supported with body_hash signing.'))
  }
 
  var shasum = crypto.createHash('sha1')
  shasum.update(body || '')
  var sha1 = shasum.digest('hex')
 
  return new Buffer(sha1).toString('base64')
}
 
OAuth.prototype.concatParams = function (oa, sep, wrap) {
  wrap = wrap || ''
 
  var params = Object.keys(oa).filter(function (i) {
    return i !== 'realm' && i !== 'oauth_signature'
  }).sort()
 
  if (oa.realm) {
    params.splice(0, 1, 'realm')
  }
  params.push('oauth_signature')
 
  return params.map(function (i) {
    return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
  }).join(sep)
}
 
OAuth.prototype.onRequest = function (_oauth) {
  var self = this
  self.params = _oauth
 
  var uri = self.request.uri || {}
    , method = self.request.method || ''
    , headers = caseless(self.request.headers)
    , body = self.request.body || ''
    , qsLib = self.request.qsLib || qs
 
  var form
    , query
    , contentType = headers.get('content-type') || ''
    , formContentType = 'application/x-www-form-urlencoded'
    , transport = _oauth.transport_method || 'header'
 
  if (contentType.slice(0, formContentType.length) === formContentType) {
    contentType = formContentType
    form = body
  }
  if (uri.query) {
    query = uri.query
  }
  if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
    self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
      'and content-type ' + formContentType))
  }
 
  if (!form && typeof _oauth.body_hash === 'boolean') {
    _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
  }
 
  var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
 
  switch (transport) {
    case 'header':
      self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
      break
 
    case 'query':
      self.request.path = (query ? '&' : '?') + self.concatParams(oa, '&')
      break
 
    case 'body':
      self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
      break
 
    default:
      self.request.emit('error', new Error('oauth: transport_method invalid'))
  }
}
 
exports.OAuth = OAuth
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/querystring.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/querystring.js

Statements: 34.78% (8 / 23)      Branches: 0% (0 / 20)      Functions: 0% (0 / 6)      Lines: 36.36% (8 / 22)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53    1       1               1                   1                 1                 1           1   1    
'use strict'
 
var qs = require('qs')
  , querystring = require('querystring')
 
 
function Querystring (request) {
  this.request = request
  this.lib = null
  this.useQuerystring = null
  this.parseOptions = null
  this.stringifyOptions = null
}
 
Querystring.prototype.init = function (options) {
  if (this.lib) {return}
 
  this.useQuerystring = options.useQuerystring
  this.lib = (this.useQuerystring ? querystring : qs)
 
  this.parseOptions = options.qsParseOptions || {}
  this.stringifyOptions = options.qsStringifyOptions || {}
}
 
Querystring.prototype.stringify = function (obj) {
  return (this.useQuerystring)
    ? this.rfc3986(this.lib.stringify(obj,
      this.stringifyOptions.sep || null,
      this.stringifyOptions.eq || null,
      this.stringifyOptions))
    : this.lib.stringify(obj, this.stringifyOptions)
}
 
Querystring.prototype.parse = function (str) {
  return (this.useQuerystring)
    ? this.lib.parse(str,
      this.parseOptions.sep || null,
      this.parseOptions.eq || null,
      this.parseOptions)
    : this.lib.parse(str, this.parseOptions)
}
 
Querystring.prototype.rfc3986 = function (str) {
  return str.replace(/[!'()*]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  })
}
 
Querystring.prototype.unescape = querystring.unescape
 
exports.Querystring = Querystring
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/redirect.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/lib/redirect.js

Statements: 8.14% (7 / 86)      Branches: 0% (0 / 61)      Functions: 0% (0 / 5)      Lines: 8.24% (7 / 85)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155    1 1   1                       1                                             1                                                                   1                                                                                                                                                           1    
'use strict'
 
var url = require('url')
var isUrl = /^https?:/
 
function Redirect (request) {
  this.request = request
  this.followRedirect = true
  this.followRedirects = true
  this.followAllRedirects = false
  this.allowRedirect = function () {return true}
  this.maxRedirects = 10
  this.redirects = []
  this.redirectsFollowed = 0
  this.removeRefererHeader = false
}
 
Redirect.prototype.onRequest = function (options) {
  var self = this
 
  if (options.maxRedirects !== undefined) {
    self.maxRedirects = options.maxRedirects
  }
  if (typeof options.followRedirect === 'function') {
    self.allowRedirect = options.followRedirect
  }
  if (options.followRedirect !== undefined) {
    self.followRedirects = !!options.followRedirect
  }
  if (options.followAllRedirects !== undefined) {
    self.followAllRedirects = options.followAllRedirects
  }
  if (self.followRedirects || self.followAllRedirects) {
    self.redirects = self.redirects || []
  }
  if (options.removeRefererHeader !== undefined) {
    self.removeRefererHeader = options.removeRefererHeader
  }
}
 
Redirect.prototype.redirectTo = function (response) {
  var self = this
    , request = self.request
 
  var redirectTo = null
  if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
    var location = response.caseless.get('location')
    request.debug('redirect', location)
 
    if (self.followAllRedirects) {
      redirectTo = location
    } else if (self.followRedirects) {
      switch (request.method) {
        case 'PATCH':
        case 'PUT':
        case 'POST':
        case 'DELETE':
          // Do not follow redirects
          break
        default:
          redirectTo = location
          break
      }
    }
  } else if (response.statusCode === 401) {
    var authHeader = request._auth.onResponse(response)
    if (authHeader) {
      request.setHeader('authorization', authHeader)
      redirectTo = request.uri
    }
  }
  return redirectTo
}
 
Redirect.prototype.onResponse = function (response) {
  var self = this
    , request = self.request
 
  var redirectTo = self.redirectTo(response)
  if (!redirectTo || !self.allowRedirect.call(request, response)) {
    return false
  }
 
  request.debug('redirect to', redirectTo)
 
  // ignore any potential response body.  it cannot possibly be useful
  // to us at this point.
  // response.resume should be defined, but check anyway before calling. Workaround for browserify.
  if (response.resume) {
    response.resume()
  }
 
  if (self.redirectsFollowed >= self.maxRedirects) {
    request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
    return false
  }
  self.redirectsFollowed += 1
 
  if (!isUrl.test(redirectTo)) {
    redirectTo = url.resolve(request.uri.href, redirectTo)
  }
 
  var uriPrev = request.uri
  request.uri = url.parse(redirectTo)
 
  // handle the case where we change protocol from https to http or vice versa
  if (request.uri.protocol !== uriPrev.protocol) {
    request._updateProtocol()
  }
 
  self.redirects.push(
    { statusCode : response.statusCode
    , redirectUri: redirectTo
    }
  )
  if (self.followAllRedirects && response.statusCode !== 401 && response.statusCode !== 307) {
    request.method = 'GET'
  }
  // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
  delete request.src
  delete request.req
  delete request.agent
  delete request._started
  if (response.statusCode !== 401 && response.statusCode !== 307) {
    // Remove parameters from the previous response, unless this is the second request
    // for a server that requires digest authentication.
    delete request.body
    delete request._form
    if (request.headers) {
      request.removeHeader('host')
      request.removeHeader('content-type')
      request.removeHeader('content-length')
      if (request.uri.hostname !== request.originalHost.split(':')[0]) {
        // Remove authorization if changing hostnames (but not if just
        // changing ports or protocols).  This matches the behavior of curl:
        // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
        request.removeHeader('authorization')
      }
    }
  }
 
  if (!self.removeRefererHeader) {
    request.setHeader('referer', request.uri.href)
  }
 
  request.emit('redirect')
 
  request.init()
 
  return true
}
 
exports.Redirect = Redirect
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/aws-sign2/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/aws-sign2/

Statements: 42.22% (19 / 45)      Branches: 0% (0 / 14)      Functions: 0% (0 / 9)      Lines: 45.24% (19 / 42)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/aws-sign2/
File Statements Branches Functions Lines
index.js 42.22% (19 / 45) 0% (0 / 14) 0% (0 / 9) 45.24% (19 / 42)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/aws-sign2/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/aws-sign2/index.js

Statements: 42.22% (19 / 45)      Branches: 0% (0 / 14)      Functions: 0% (0 / 9)      Lines: 45.24% (19 / 42)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204                      1               1                                                   1       1 1                   1       1                   1       1                       1       1                                     1                       1                               1     1                               1                           1                         1                           1    
 
/*!
 * knox - auth
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */
 
/**
 * Module dependencies.
 */
 
var crypto = require('crypto')
  , parse = require('url').parse
  ;
 
/**
 * Valid keys.
 */
 
var keys = 
  [ 'acl'
  , 'location'
  , 'logging'
  , 'notification'
  , 'partNumber'
  , 'policy'
  , 'requestPayment'
  , 'torrent'
  , 'uploadId'
  , 'uploads'
  , 'versionId'
  , 'versioning'
  , 'versions'
  , 'website'
  ]
 
/**
 * Return an "Authorization" header value with the given `options`
 * in the form of "AWS <key>:<signature>"
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function authorization (options) {
  return 'AWS ' + options.key + ':' + sign(options)
}
 
module.exports = authorization
module.exports.authorization = authorization
 
/**
 * Simple HMAC-SHA1 Wrapper
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */ 
 
function hmacSha1 (options) {
  return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
}
 
module.exports.hmacSha1 = hmacSha1
 
/**
 * Create a base64 sha1 HMAC for `options`. 
 * 
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function sign (options) {
  options.message = stringToSign(options)
  return hmacSha1(options)
}
module.exports.sign = sign
 
/**
 * Create a base64 sha1 HMAC for `options`. 
 *
 * Specifically to be used with S3 presigned URLs
 * 
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function signQuery (options) {
  options.message = queryStringToSign(options)
  return hmacSha1(options)
}
module.exports.signQuery= signQuery
 
/**
 * Return a string for sign() with the given `options`.
 *
 * Spec:
 * 
 *    <verb>\n
 *    <md5>\n
 *    <content-type>\n
 *    <date>\n
 *    [headers\n]
 *    <resource>
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function stringToSign (options) {
  var headers = options.amazonHeaders || ''
  if (headers) headers += '\n'
  var r = 
    [ options.verb
    , options.md5
    , options.contentType
    , options.date ? options.date.toUTCString() : ''
    , headers + options.resource
    ]
  return r.join('\n')
}
module.exports.queryStringToSign = stringToSign
 
/**
 * Return a string for sign() with the given `options`, but is meant exclusively
 * for S3 presigned URLs
 *
 * Spec:
 * 
 *    <date>\n
 *    <resource>
 *
 * @param {Object} options
 * @return {String}
 * @api private
 */
 
function queryStringToSign (options){
  return 'GET\n\n\n' + options.date + '\n' + options.resource
}
module.exports.queryStringToSign = queryStringToSign
 
/**
 * Perform the following:
 *
 *  - ignore non-amazon headers
 *  - lowercase fields
 *  - sort lexicographically
 *  - trim whitespace between ":"
 *  - join with newline
 *
 * @param {Object} headers
 * @return {String}
 * @api private
 */
 
function canonicalizeHeaders (headers) {
  var buf = []
    , fields = Object.keys(headers)
    ;
  for (var i = 0, len = fields.length; i < len; ++i) {
    var field = fields[i]
      , val = headers[field]
      , field = field.toLowerCase()
      ;
    if (0 !== field.indexOf('x-amz')) continue
    buf.push(field + ':' + val)
  }
  return buf.sort().join('\n')
}
module.exports.canonicalizeHeaders = canonicalizeHeaders
 
/**
 * Perform the following:
 *
 *  - ignore non sub-resources
 *  - sort lexicographically
 *
 * @param {String} resource
 * @return {String}
 * @api private
 */
 
function canonicalizeResource (resource) {
  var url = parse(resource, true)
    , path = url.pathname
    , buf = []
    ;
 
  Object.keys(url.query).forEach(function(key){
    if (!~keys.indexOf(key)) return
    var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
    buf.push(key + val)
  })
 
  return path + (buf.length ? '?' + buf.sort().join('&') : '')
}
module.exports.canonicalizeResource = canonicalizeResource
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/

Statements: 18.42% (21 / 114)      Branches: 0% (0 / 61)      Functions: 10% (2 / 20)      Lines: 18.42% (21 / 114)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/
File Statements Branches Functions Lines
bl.js 18.42% (21 / 114) 0% (0 / 61) 10% (2 / 20) 18.42% (21 / 114)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/bl.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/bl.js

Statements: 18.42% (21 / 114)      Branches: 0% (0 / 61)      Functions: 10% (2 / 20)      Lines: 18.42% (21 / 114)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 2181     1                                                                     1   1                   1                 1           1               1                 1       1       1                                                                                                                             1       1                             1                   1           1 1                                 1 14 14             1    
var DuplexStream = require('readable-stream/duplex')
  , util         = require('util')
 
function BufferList (callback) {
  if (!(this instanceof BufferList))
    return new BufferList(callback)
 
  this._bufs  = []
  this.length = 0
 
  if (typeof callback == 'function') {
    this._callback = callback
 
    var piper = function (err) {
      if (this._callback) {
        this._callback(err)
        this._callback = null
      }
    }.bind(this)
 
    this.on('pipe', function (src) {
      src.on('error', piper)
    })
    this.on('unpipe', function (src) {
      src.removeListener('error', piper)
    })
  }
  else if (Buffer.isBuffer(callback))
    this.append(callback)
  else if (Array.isArray(callback)) {
    callback.forEach(function (b) {
      Buffer.isBuffer(b) && this.append(b)
    }.bind(this))
  }
 
  DuplexStream.call(this)
}
 
util.inherits(BufferList, DuplexStream)
 
BufferList.prototype._offset = function (offset) {
  var tot = 0, i = 0, _t
  for (; i < this._bufs.length; i++) {
    _t = tot + this._bufs[i].length
    if (offset < _t)
      return [ i, offset - tot ]
    tot = _t
  }
}
 
BufferList.prototype.append = function (buf) {
  var isBuffer = Buffer.isBuffer(buf) ||
                 buf instanceof BufferList
 
  this._bufs.push(isBuffer ? buf : new Buffer(buf))
  this.length += buf.length
  return this
}
 
BufferList.prototype._write = function (buf, encoding, callback) {
  this.append(buf)
  if (callback)
    callback()
}
 
BufferList.prototype._read = function (size) {
  if (!this.length)
    return this.push(null)
  size = Math.min(size, this.length)
  this.push(this.slice(0, size))
  this.consume(size)
}
 
BufferList.prototype.end = function (chunk) {
  DuplexStream.prototype.end.call(this, chunk)
 
  if (this._callback) {
    this._callback(null, this.slice())
    this._callback = null
  }
}
 
BufferList.prototype.get = function (index) {
  return this.slice(index, index + 1)[0]
}
 
BufferList.prototype.slice = function (start, end) {
  return this.copy(null, 0, start, end)
}
 
BufferList.prototype.copy = function (dst, dstStart, srcStart, srcEnd) {
  if (typeof srcStart != 'number' || srcStart < 0)
    srcStart = 0
  if (typeof srcEnd != 'number' || srcEnd > this.length)
    srcEnd = this.length
  if (srcStart >= this.length)
    return dst || new Buffer(0)
  if (srcEnd <= 0)
    return dst || new Buffer(0)
 
  var copy   = !!dst
    , off    = this._offset(srcStart)
    , len    = srcEnd - srcStart
    , bytes  = len
    , bufoff = (copy && dstStart) || 0
    , start  = off[1]
    , l
    , i
 
  // copy/slice everything
  if (srcStart === 0 && srcEnd == this.length) {
    if (!copy) // slice, just return a full concat
      return Buffer.concat(this._bufs)
 
    // copy, need to copy individual buffers
    for (i = 0; i < this._bufs.length; i++) {
      this._bufs[i].copy(dst, bufoff)
      bufoff += this._bufs[i].length
    }
 
    return dst
  }
 
  // easy, cheap case where it's a subset of one of the buffers
  if (bytes <= this._bufs[off[0]].length - start) {
    return copy
      ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
      : this._bufs[off[0]].slice(start, start + bytes)
  }
 
  if (!copy) // a slice, we need something to copy in to
    dst = new Buffer(len)
 
  for (i = off[0]; i < this._bufs.length; i++) {
    l = this._bufs[i].length - start
 
    if (bytes > l) {
      this._bufs[i].copy(dst, bufoff, start)
    } else {
      this._bufs[i].copy(dst, bufoff, start, start + bytes)
      break
    }
 
    bufoff += l
    bytes -= l
 
    if (start)
      start = 0
  }
 
  return dst
}
 
BufferList.prototype.toString = function (encoding, start, end) {
  return this.slice(start, end).toString(encoding)
}
 
BufferList.prototype.consume = function (bytes) {
  while (this._bufs.length) {
    if (bytes > this._bufs[0].length) {
      bytes -= this._bufs[0].length
      this.length -= this._bufs[0].length
      this._bufs.shift()
    } else {
      this._bufs[0] = this._bufs[0].slice(bytes)
      this.length -= bytes
      break
    }
  }
  return this
}
 
BufferList.prototype.duplicate = function () {
  var i = 0
    , copy = new BufferList()
 
  for (; i < this._bufs.length; i++)
    copy.append(this._bufs[i])
 
  return copy
}
 
BufferList.prototype.destroy = function () {
  this._bufs.length = 0;
  this.length = 0;
  this.push(null);
}
 
;(function () {
  var methods = {
      'readDoubleBE' : 8
    , 'readDoubleLE' : 8
    , 'readFloatBE'  : 4
    , 'readFloatLE'  : 4
    , 'readInt32BE'  : 4
    , 'readInt32LE'  : 4
    , 'readUInt32BE' : 4
    , 'readUInt32LE' : 4
    , 'readInt16BE'  : 2
    , 'readInt16LE'  : 2
    , 'readUInt16BE' : 2
    , 'readUInt16LE' : 2
    , 'readInt8'     : 1
    , 'readUInt8'    : 1
  }
 
  for (var m in methods) {
    (function (m) {
      BufferList.prototype[m] = function (offset) {
        return this.slice(offset, offset + methods[m])[m](0)
      }
    }(m))
  }
}())
 
module.exports = BufferList
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/
File Statements Branches Functions Lines
duplex.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/duplex.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/duplex.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require("./lib/_stream_duplex.js")
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/

Statements: 13.77% (96 / 697)      Branches: 0.93% (4 / 430)      Functions: 2.3% (2 / 87)      Lines: 13.89% (96 / 691)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/
File Statements Branches Functions Lines
_stream_duplex.js 44.12% (15 / 34) 13.64% (3 / 22) 40% (2 / 5) 45.45% (15 / 33)
_stream_readable.js 11% (53 / 482) 0.32% (1 / 317) 0% (0 / 55) 11.11% (53 / 477)
_stream_writable.js 15.47% (28 / 181) 0% (0 / 91) 0% (0 / 27) 15.47% (28 / 181)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js

Statements: 44.12% (15 / 34)      Branches: 13.64% (3 / 22)      Functions: 40% (2 / 5)      Lines: 45.45% (15 / 33)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91                                                    1     1                 1 1     1 1   1   1 4 3     1                                         1                     1 1 4        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
 
module.exports = Duplex;
 
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
  var keys = [];
  for (var key in obj) keys.push(key);
  return keys;
}
/*</replacement>*/
 
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
 
util.inherits(Duplex, Readable);
 
forEach(objectKeys(Writable.prototype), function(method) {
  if (!Duplex.prototype[method])
    Duplex.prototype[method] = Writable.prototype[method];
});
 
function Duplex(options) {
  if (!(this instanceof Duplex))
    return new Duplex(options);
 
  Readable.call(this, options);
  Writable.call(this, options);
 
  if (options && options.readable === false)
    this.readable = false;
 
  if (options && options.writable === false)
    this.writable = false;
 
  this.allowHalfOpen = true;
  if (options && options.allowHalfOpen === false)
    this.allowHalfOpen = false;
 
  this.once('end', onend);
}
 
// the no-half-open enforcer
function onend() {
  // if we allow half-open state, or if the writable side ended,
  // then we're ok.
  if (this.allowHalfOpen || this._writableState.ended)
    return;
 
  // no more data can be written.
  // But allow more writes to happen in this tick.
  process.nextTick(this.end.bind(this));
}
 
function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_readable.js

Statements: 11% (53 / 482)      Branches: 0.32% (1 / 317)      Functions: 0% (0 / 55)      Lines: 11.11% (53 / 477)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984                                          1     1         1     1   1     1         1     1 1     1   1   1                                                                                                                                       1                               1                             1         1                                                                                                 1               1               1 1                       1                                                                           1                                                                                                                                                                                                                                                       1                         1                                         1                             1                     1                 1                                   1       1                                                       1         1                     1                                         1                                   1         1           1                                               1                   1         1                                                                             1               1                                                                                                                     1                                           1       1           1         1                                                                                                       1                                                                                                                                 1       1                                                                                                                               1                                         1           1              
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
module.exports = Readable;
 
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
 
 
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
 
Readable.ReadableState = ReadableState;
 
var EE = require('events').EventEmitter;
 
/*<replacement>*/
Iif (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/
 
var Stream = require('stream');
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var StringDecoder;
 
util.inherits(Readable, Stream);
 
function ReadableState(options, stream) {
  options = options || {};
 
  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  this.buffer = [];
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = false;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;
 
  // In streams that never have any data, and do push(null) right away,
  // the consumer can miss the 'end' event if they do some I/O before
  // consuming the stream.  So, we don't emit('end') until some reading
  // happens.
  this.calledRead = false;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, becuase any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;
 
 
  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // when piping, we only care about 'readable' events that happen
  // after read()ing all the bytes and not getting any pushback.
  this.ranOut = false;
 
  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;
 
  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;
 
  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder)
      StringDecoder = require('string_decoder/').StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}
 
function Readable(options) {
  if (!(this instanceof Readable))
    return new Readable(options);
 
  this._readableState = new ReadableState(options, this);
 
  // legacy
  this.readable = true;
 
  Stream.call(this);
}
 
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
  var state = this._readableState;
 
  if (typeof chunk === 'string' && !state.objectMode) {
    encoding = encoding || state.defaultEncoding;
    if (encoding !== state.encoding) {
      chunk = new Buffer(chunk, encoding);
      encoding = '';
    }
  }
 
  return readableAddChunk(this, state, chunk, encoding, false);
};
 
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
  var state = this._readableState;
  return readableAddChunk(this, state, chunk, '', true);
};
 
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  var er = chunkInvalid(state, chunk);
  if (er) {
    stream.emit('error', er);
  } else if (chunk === null || chunk === undefined) {
    state.reading = false;
    if (!state.ended)
      onEofChunk(stream, state);
  } else if (state.objectMode || chunk && chunk.length > 0) {
    if (state.ended && !addToFront) {
      var e = new Error('stream.push() after EOF');
      stream.emit('error', e);
    } else if (state.endEmitted && addToFront) {
      var e = new Error('stream.unshift() after end event');
      stream.emit('error', e);
    } else {
      if (state.decoder && !addToFront && !encoding)
        chunk = state.decoder.write(chunk);
 
      // update the buffer info.
      state.length += state.objectMode ? 1 : chunk.length;
      if (addToFront) {
        state.buffer.unshift(chunk);
      } else {
        state.reading = false;
        state.buffer.push(chunk);
      }
 
      if (state.needReadable)
        emitReadable(stream);
 
      maybeReadMore(stream, state);
    }
  } else if (!addToFront) {
    state.reading = false;
  }
 
  return needMoreData(state);
}
 
 
 
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended &&
         (state.needReadable ||
          state.length < state.highWaterMark ||
          state.length === 0);
}
 
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
  if (!StringDecoder)
    StringDecoder = require('string_decoder/').StringDecoder;
  this._readableState.decoder = new StringDecoder(enc);
  this._readableState.encoding = enc;
};
 
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
  if (n >= MAX_HWM) {
    n = MAX_HWM;
  } else {
    // Get the next highest power of 2
    n--;
    for (var p = 1; p < 32; p <<= 1) n |= n >> p;
    n++;
  }
  return n;
}
 
function howMuchToRead(n, state) {
  if (state.length === 0 && state.ended)
    return 0;
 
  if (state.objectMode)
    return n === 0 ? 0 : 1;
 
  if (n === null || isNaN(n)) {
    // only flow one buffer at a time
    if (state.flowing && state.buffer.length)
      return state.buffer[0].length;
    else
      return state.length;
  }
 
  if (n <= 0)
    return 0;
 
  // If we're asking for more than the target buffer level,
  // then raise the water mark.  Bump up to the next highest
  // power of 2, to prevent increasing it excessively in tiny
  // amounts.
  if (n > state.highWaterMark)
    state.highWaterMark = roundUpToNextPowerOf2(n);
 
  // don't have that much.  return null, unless we've ended.
  if (n > state.length) {
    if (!state.ended) {
      state.needReadable = true;
      return 0;
    } else
      return state.length;
  }
 
  return n;
}
 
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
  var state = this._readableState;
  state.calledRead = true;
  var nOrig = n;
  var ret;
 
  if (typeof n !== 'number' || n > 0)
    state.emittedReadable = false;
 
  // if we're doing read(0) to trigger a readable event, but we
  // already have a bunch of data in the buffer, then just trigger
  // the 'readable' event and move on.
  if (n === 0 &&
      state.needReadable &&
      (state.length >= state.highWaterMark || state.ended)) {
    emitReadable(this);
    return null;
  }
 
  n = howMuchToRead(n, state);
 
  // if we've ended, and we're now clear, then finish it up.
  if (n === 0 && state.ended) {
    ret = null;
 
    // In cases where the decoder did not receive enough data
    // to produce a full chunk, then immediately received an
    // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>].
    // howMuchToRead will see this and coerce the amount to
    // read to zero (because it's looking at the length of the
    // first <Buffer > in state.buffer), and we'll end up here.
    //
    // This can only happen via state.decoder -- no other venue
    // exists for pushing a zero-length chunk into state.buffer
    // and triggering this behavior. In this case, we return our
    // remaining data and end the stream, if appropriate.
    if (state.length > 0 && state.decoder) {
      ret = fromList(n, state);
      state.length -= ret.length;
    }
 
    if (state.length === 0)
      endReadable(this);
 
    return ret;
  }
 
  // All the actual chunk generation logic needs to be
  // *below* the call to _read.  The reason is that in certain
  // synthetic stream cases, such as passthrough streams, _read
  // may be a completely synchronous operation which may change
  // the state of the read buffer, providing enough data when
  // before there was *not* enough.
  //
  // So, the steps are:
  // 1. Figure out what the state of things will be after we do
  // a read from the buffer.
  //
  // 2. If that resulting state will trigger a _read, then call _read.
  // Note that this may be asynchronous, or synchronous.  Yes, it is
  // deeply ugly to write APIs this way, but that still doesn't mean
  // that the Readable class should behave improperly, as streams are
  // designed to be sync/async agnostic.
  // Take note if the _read call is sync or async (ie, if the read call
  // has returned yet), so that we know whether or not it's safe to emit
  // 'readable' etc.
  //
  // 3. Actually pull the requested chunks out of the buffer and return.
 
  // if we need a readable event, then we need to do some reading.
  var doRead = state.needReadable;
 
  // if we currently have less than the highWaterMark, then also read some
  if (state.length - n <= state.highWaterMark)
    doRead = true;
 
  // however, if we've ended, then there's no point, and if we're already
  // reading, then it's unnecessary.
  if (state.ended || state.reading)
    doRead = false;
 
  if (doRead) {
    state.reading = true;
    state.sync = true;
    // if the length is currently zero, then we *need* a readable event.
    if (state.length === 0)
      state.needReadable = true;
    // call internal read method
    this._read(state.highWaterMark);
    state.sync = false;
  }
 
  // If _read called its callback synchronously, then `reading`
  // will be false, and we need to re-evaluate how much data we
  // can return to the user.
  if (doRead && !state.reading)
    n = howMuchToRead(nOrig, state);
 
  if (n > 0)
    ret = fromList(n, state);
  else
    ret = null;
 
  if (ret === null) {
    state.needReadable = true;
    n = 0;
  }
 
  state.length -= n;
 
  // If we have nothing in the buffer, then we want to know
  // as soon as we *do* get something into the buffer.
  if (state.length === 0 && !state.ended)
    state.needReadable = true;
 
  // If we happened to read() exactly the remaining amount in the
  // buffer, and the EOF has been seen at this point, then make sure
  // that we emit 'end' on the very next tick.
  if (state.ended && !state.endEmitted && state.length === 0)
    endReadable(this);
 
  return ret;
};
 
function chunkInvalid(state, chunk) {
  var er = null;
  if (!Buffer.isBuffer(chunk) &&
      'string' !== typeof chunk &&
      chunk !== null &&
      chunk !== undefined &&
      !state.objectMode) {
    er = new TypeError('Invalid non-string/buffer chunk');
  }
  return er;
}
 
 
function onEofChunk(stream, state) {
  if (state.decoder && !state.ended) {
    var chunk = state.decoder.end();
    if (chunk && chunk.length) {
      state.buffer.push(chunk);
      state.length += state.objectMode ? 1 : chunk.length;
    }
  }
  state.ended = true;
 
  // if we've ended and we have some data left, then emit
  // 'readable' now to make sure it gets picked up.
  if (state.length > 0)
    emitReadable(stream);
  else
    endReadable(stream);
}
 
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow.  This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
  var state = stream._readableState;
  state.needReadable = false;
  if (state.emittedReadable)
    return;
 
  state.emittedReadable = true;
  if (state.sync)
    process.nextTick(function() {
      emitReadable_(stream);
    });
  else
    emitReadable_(stream);
}
 
function emitReadable_(stream) {
  stream.emit('readable');
}
 
 
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data.  that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
  if (!state.readingMore) {
    state.readingMore = true;
    process.nextTick(function() {
      maybeReadMore_(stream, state);
    });
  }
}
 
function maybeReadMore_(stream, state) {
  var len = state.length;
  while (!state.reading && !state.flowing && !state.ended &&
         state.length < state.highWaterMark) {
    stream.read(0);
    if (len === state.length)
      // didn't get any data, stop spinning.
      break;
    else
      len = state.length;
  }
  state.readingMore = false;
}
 
// abstract method.  to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
  this.emit('error', new Error('not implemented'));
};
 
Readable.prototype.pipe = function(dest, pipeOpts) {
  var src = this;
  var state = this._readableState;
 
  switch (state.pipesCount) {
    case 0:
      state.pipes = dest;
      break;
    case 1:
      state.pipes = [state.pipes, dest];
      break;
    default:
      state.pipes.push(dest);
      break;
  }
  state.pipesCount += 1;
 
  var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
              dest !== process.stdout &&
              dest !== process.stderr;
 
  var endFn = doEnd ? onend : cleanup;
  if (state.endEmitted)
    process.nextTick(endFn);
  else
    src.once('end', endFn);
 
  dest.on('unpipe', onunpipe);
  function onunpipe(readable) {
    if (readable !== src) return;
    cleanup();
  }
 
  function onend() {
    dest.end();
  }
 
  // when the dest drains, it reduces the awaitDrain counter
  // on the source.  This would be more elegant with a .once()
  // handler in flow(), but adding and removing repeatedly is
  // too slow.
  var ondrain = pipeOnDrain(src);
  dest.on('drain', ondrain);
 
  function cleanup() {
    // cleanup event handlers once the pipe is broken
    dest.removeListener('close', onclose);
    dest.removeListener('finish', onfinish);
    dest.removeListener('drain', ondrain);
    dest.removeListener('error', onerror);
    dest.removeListener('unpipe', onunpipe);
    src.removeListener('end', onend);
    src.removeListener('end', cleanup);
 
    // if the reader is waiting for a drain event from this
    // specific writer, then it would cause it to never start
    // flowing again.
    // So, if this is awaiting a drain, then we just call it now.
    // If we don't know, then assume that we are waiting for one.
    if (!dest._writableState || dest._writableState.needDrain)
      ondrain();
  }
 
  // if the dest has an error, then stop piping into it.
  // however, don't suppress the throwing behavior for this.
  function onerror(er) {
    unpipe();
    dest.removeListener('error', onerror);
    if (EE.listenerCount(dest, 'error') === 0)
      dest.emit('error', er);
  }
  // This is a brutally ugly hack to make sure that our error handler
  // is attached before any userland ones.  NEVER DO THIS.
  if (!dest._events || !dest._events.error)
    dest.on('error', onerror);
  else if (isArray(dest._events.error))
    dest._events.error.unshift(onerror);
  else
    dest._events.error = [onerror, dest._events.error];
 
 
 
  // Both close and finish should trigger unpipe, but only once.
  function onclose() {
    dest.removeListener('finish', onfinish);
    unpipe();
  }
  dest.once('close', onclose);
  function onfinish() {
    dest.removeListener('close', onclose);
    unpipe();
  }
  dest.once('finish', onfinish);
 
  function unpipe() {
    src.unpipe(dest);
  }
 
  // tell the dest that it's being piped to
  dest.emit('pipe', src);
 
  // start the flow if it hasn't been started already.
  if (!state.flowing) {
    // the handler that waits for readable events after all
    // the data gets sucked out in flow.
    // This would be easier to follow with a .once() handler
    // in flow(), but that is too slow.
    this.on('readable', pipeOnReadable);
 
    state.flowing = true;
    process.nextTick(function() {
      flow(src);
    });
  }
 
  return dest;
};
 
function pipeOnDrain(src) {
  return function() {
    var dest = this;
    var state = src._readableState;
    state.awaitDrain--;
    if (state.awaitDrain === 0)
      flow(src);
  };
}
 
function flow(src) {
  var state = src._readableState;
  var chunk;
  state.awaitDrain = 0;
 
  function write(dest, i, list) {
    var written = dest.write(chunk);
    if (false === written) {
      state.awaitDrain++;
    }
  }
 
  while (state.pipesCount && null !== (chunk = src.read())) {
 
    if (state.pipesCount === 1)
      write(state.pipes, 0, null);
    else
      forEach(state.pipes, write);
 
    src.emit('data', chunk);
 
    // if anyone needs a drain, then we have to wait for that.
    if (state.awaitDrain > 0)
      return;
  }
 
  // if every destination was unpiped, either before entering this
  // function, or in the while loop, then stop flowing.
  //
  // NB: This is a pretty rare edge case.
  if (state.pipesCount === 0) {
    state.flowing = false;
 
    // if there were data event listeners added, then switch to old mode.
    if (EE.listenerCount(src, 'data') > 0)
      emitDataEvents(src);
    return;
  }
 
  // at this point, no one needed a drain, so we just ran out of data
  // on the next readable event, start it over again.
  state.ranOut = true;
}
 
function pipeOnReadable() {
  if (this._readableState.ranOut) {
    this._readableState.ranOut = false;
    flow(this);
  }
}
 
 
Readable.prototype.unpipe = function(dest) {
  var state = this._readableState;
 
  // if we're not piping anywhere, then do nothing.
  if (state.pipesCount === 0)
    return this;
 
  // just one destination.  most common case.
  if (state.pipesCount === 1) {
    // passed in one, but it's not the right one.
    if (dest && dest !== state.pipes)
      return this;
 
    if (!dest)
      dest = state.pipes;
 
    // got a match.
    state.pipes = null;
    state.pipesCount = 0;
    this.removeListener('readable', pipeOnReadable);
    state.flowing = false;
    if (dest)
      dest.emit('unpipe', this);
    return this;
  }
 
  // slow case. multiple pipe destinations.
 
  if (!dest) {
    // remove all.
    var dests = state.pipes;
    var len = state.pipesCount;
    state.pipes = null;
    state.pipesCount = 0;
    this.removeListener('readable', pipeOnReadable);
    state.flowing = false;
 
    for (var i = 0; i < len; i++)
      dests[i].emit('unpipe', this);
    return this;
  }
 
  // try to find the right one.
  var i = indexOf(state.pipes, dest);
  if (i === -1)
    return this;
 
  state.pipes.splice(i, 1);
  state.pipesCount -= 1;
  if (state.pipesCount === 1)
    state.pipes = state.pipes[0];
 
  dest.emit('unpipe', this);
 
  return this;
};
 
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
  var res = Stream.prototype.on.call(this, ev, fn);
 
  if (ev === 'data' && !this._readableState.flowing)
    emitDataEvents(this);
 
  if (ev === 'readable' && this.readable) {
    var state = this._readableState;
    if (!state.readableListening) {
      state.readableListening = true;
      state.emittedReadable = false;
      state.needReadable = true;
      if (!state.reading) {
        this.read(0);
      } else if (state.length) {
        emitReadable(this, state);
      }
    }
  }
 
  return res;
};
Readable.prototype.addListener = Readable.prototype.on;
 
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
  emitDataEvents(this);
  this.read(0);
  this.emit('resume');
};
 
Readable.prototype.pause = function() {
  emitDataEvents(this, true);
  this.emit('pause');
};
 
function emitDataEvents(stream, startPaused) {
  var state = stream._readableState;
 
  if (state.flowing) {
    // https://github.com/isaacs/readable-stream/issues/16
    throw new Error('Cannot switch to old mode now.');
  }
 
  var paused = startPaused || false;
  var readable = false;
 
  // convert to an old-style stream.
  stream.readable = true;
  stream.pipe = Stream.prototype.pipe;
  stream.on = stream.addListener = Stream.prototype.on;
 
  stream.on('readable', function() {
    readable = true;
 
    var c;
    while (!paused && (null !== (c = stream.read())))
      stream.emit('data', c);
 
    if (c === null) {
      readable = false;
      stream._readableState.needReadable = true;
    }
  });
 
  stream.pause = function() {
    paused = true;
    this.emit('pause');
  };
 
  stream.resume = function() {
    paused = false;
    if (readable)
      process.nextTick(function() {
        stream.emit('readable');
      });
    else
      this.read(0);
    this.emit('resume');
  };
 
  // now make it start, just in case it hadn't already.
  stream.emit('readable');
}
 
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
  var state = this._readableState;
  var paused = false;
 
  var self = this;
  stream.on('end', function() {
    if (state.decoder && !state.ended) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length)
        self.push(chunk);
    }
 
    self.push(null);
  });
 
  stream.on('data', function(chunk) {
    if (state.decoder)
      chunk = state.decoder.write(chunk);
 
    // don't skip over falsy values in objectMode
    //if (state.objectMode && util.isNullOrUndefined(chunk))
    if (state.objectMode && (chunk === null || chunk === undefined))
      return;
    else if (!state.objectMode && (!chunk || !chunk.length))
      return;
 
    var ret = self.push(chunk);
    if (!ret) {
      paused = true;
      stream.pause();
    }
  });
 
  // proxy all the other methods.
  // important when wrapping filters and duplexes.
  for (var i in stream) {
    if (typeof stream[i] === 'function' &&
        typeof this[i] === 'undefined') {
      this[i] = function(method) { return function() {
        return stream[method].apply(stream, arguments);
      }}(i);
    }
  }
 
  // proxy certain important events.
  var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  forEach(events, function(ev) {
    stream.on(ev, self.emit.bind(self, ev));
  });
 
  // when we try to consume some more bytes, simply unpause the
  // underlying stream.
  self._read = function(n) {
    if (paused) {
      paused = false;
      stream.resume();
    }
  };
 
  return self;
};
 
 
 
// exposed for testing purposes only.
Readable._fromList = fromList;
 
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
  var list = state.buffer;
  var length = state.length;
  var stringMode = !!state.decoder;
  var objectMode = !!state.objectMode;
  var ret;
 
  // nothing in the list, definitely empty.
  if (list.length === 0)
    return null;
 
  if (length === 0)
    ret = null;
  else if (objectMode)
    ret = list.shift();
  else if (!n || n >= length) {
    // read it all, truncate the array.
    if (stringMode)
      ret = list.join('');
    else
      ret = Buffer.concat(list, length);
    list.length = 0;
  } else {
    // read just some of it.
    if (n < list[0].length) {
      // just take a part of the first list item.
      // slice is the same for buffers and strings.
      var buf = list[0];
      ret = buf.slice(0, n);
      list[0] = buf.slice(n);
    } else if (n === list[0].length) {
      // first list is a perfect match
      ret = list.shift();
    } else {
      // complex case.
      // we have enough to cover it, but it spans past the first buffer.
      if (stringMode)
        ret = '';
      else
        ret = new Buffer(n);
 
      var c = 0;
      for (var i = 0, l = list.length; i < l && c < n; i++) {
        var buf = list[0];
        var cpy = Math.min(n - c, buf.length);
 
        if (stringMode)
          ret += buf.slice(0, cpy);
        else
          buf.copy(ret, c, 0, cpy);
 
        if (cpy < buf.length)
          list[0] = buf.slice(cpy);
        else
          list.shift();
 
        c += cpy;
      }
    }
  }
 
  return ret;
}
 
function endReadable(stream) {
  var state = stream._readableState;
 
  // If we get here before consuming all the bytes, then that is a
  // bug in node.  Should never happen.
  if (state.length > 0)
    throw new Error('endReadable called on non-empty stream');
 
  if (!state.endEmitted && state.calledRead) {
    state.ended = true;
    process.nextTick(function() {
      // Check that we didn't get one last unshift.
      if (!state.endEmitted && state.length === 0) {
        state.endEmitted = true;
        stream.readable = false;
        stream.emit('end');
      }
    });
  }
}
 
function forEach (xs, f) {
  for (var i = 0, l = xs.length; i < l; i++) {
    f(xs[i], i);
  }
}
 
function indexOf (xs, x) {
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) return i;
  }
  return -1;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_writable.js

Statements: 15.47% (28 / 181)      Branches: 0% (0 / 91)      Functions: 0% (0 / 27)      Lines: 15.47% (28 / 181)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388                                                  1     1     1       1 1     1   1   1           1                                                                                                                                             1                                 1         1                           1                                 1                                                 1                       1                                         1                 1                       1             1                                                   1                     1                 1                                                         1       1                                         1             1                 1                        
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
 
module.exports = Writable;
 
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
 
Writable.WritableState = WritableState;
 
 
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
 
var Stream = require('stream');
 
util.inherits(Writable, Stream);
 
function WriteReq(chunk, encoding, cb) {
  this.chunk = chunk;
  this.encoding = encoding;
  this.callback = cb;
}
 
function WritableState(options, stream) {
  options = options || {};
 
  // the point at which write() starts returning false
  // Note: 0 is a valid value, means that we always return false if
  // the entire buffer is not flushed immediately on write()
  var hwm = options.highWaterMark;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024;
 
  // object stream flag to indicate whether or not this stream
  // contains buffers or objects.
  this.objectMode = !!options.objectMode;
 
  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;
 
  this.needDrain = false;
  // at the start of calling end()
  this.ending = false;
  // when end() has been called, and returned
  this.ended = false;
  // when 'finish' is emitted
  this.finished = false;
 
  // should we decode strings into buffers before passing to _write?
  // this is here so that some node-core streams can optimize string
  // handling at a lower level.
  var noDecode = options.decodeStrings === false;
  this.decodeStrings = !noDecode;
 
  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';
 
  // not an actual buffer we keep track of, but a measurement
  // of how much we're waiting to get pushed to some underlying
  // socket or file.
  this.length = 0;
 
  // a flag to see when we're in the middle of a write.
  this.writing = false;
 
  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, becuase any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;
 
  // a flag to know if we're processing previously buffered items, which
  // may call the _write() callback in the same tick, so that we don't
  // end up in an overlapped onwrite situation.
  this.bufferProcessing = false;
 
  // the callback that's passed to _write(chunk,cb)
  this.onwrite = function(er) {
    onwrite(stream, er);
  };
 
  // the callback that the user supplies to write(chunk,encoding,cb)
  this.writecb = null;
 
  // the amount that is being written when _write is called.
  this.writelen = 0;
 
  this.buffer = [];
 
  // True if the error was already emitted and should not be thrown again
  this.errorEmitted = false;
}
 
function Writable(options) {
  var Duplex = require('./_stream_duplex');
 
  // Writable ctor is applied to Duplexes, though they're not
  // instanceof Writable, they're instanceof Readable.
  if (!(this instanceof Writable) && !(this instanceof Duplex))
    return new Writable(options);
 
  this._writableState = new WritableState(options, this);
 
  // legacy.
  this.writable = true;
 
  Stream.call(this);
}
 
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
  this.emit('error', new Error('Cannot pipe. Not readable.'));
};
 
 
function writeAfterEnd(stream, state, cb) {
  var er = new Error('write after end');
  // TODO: defer error events consistently everywhere, not just the cb
  stream.emit('error', er);
  process.nextTick(function() {
    cb(er);
  });
}
 
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
  var valid = true;
  if (!Buffer.isBuffer(chunk) &&
      'string' !== typeof chunk &&
      chunk !== null &&
      chunk !== undefined &&
      !state.objectMode) {
    var er = new TypeError('Invalid non-string/buffer chunk');
    stream.emit('error', er);
    process.nextTick(function() {
      cb(er);
    });
    valid = false;
  }
  return valid;
}
 
Writable.prototype.write = function(chunk, encoding, cb) {
  var state = this._writableState;
  var ret = false;
 
  if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
 
  if (Buffer.isBuffer(chunk))
    encoding = 'buffer';
  else if (!encoding)
    encoding = state.defaultEncoding;
 
  if (typeof cb !== 'function')
    cb = function() {};
 
  if (state.ended)
    writeAfterEnd(this, state, cb);
  else if (validChunk(this, state, chunk, cb))
    ret = writeOrBuffer(this, state, chunk, encoding, cb);
 
  return ret;
};
 
function decodeChunk(state, chunk, encoding) {
  if (!state.objectMode &&
      state.decodeStrings !== false &&
      typeof chunk === 'string') {
    chunk = new Buffer(chunk, encoding);
  }
  return chunk;
}
 
// if we're already writing something, then just put this
// in the queue, and wait our turn.  Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
  chunk = decodeChunk(state, chunk, encoding);
  if (Buffer.isBuffer(chunk))
    encoding = 'buffer';
  var len = state.objectMode ? 1 : chunk.length;
 
  state.length += len;
 
  var ret = state.length < state.highWaterMark;
  // we must ensure that previous needDrain will not be reset to false.
  if (!ret)
    state.needDrain = true;
 
  if (state.writing)
    state.buffer.push(new WriteReq(chunk, encoding, cb));
  else
    doWrite(stream, state, len, chunk, encoding, cb);
 
  return ret;
}
 
function doWrite(stream, state, len, chunk, encoding, cb) {
  state.writelen = len;
  state.writecb = cb;
  state.writing = true;
  state.sync = true;
  stream._write(chunk, encoding, state.onwrite);
  state.sync = false;
}
 
function onwriteError(stream, state, sync, er, cb) {
  if (sync)
    process.nextTick(function() {
      cb(er);
    });
  else
    cb(er);
 
  stream._writableState.errorEmitted = true;
  stream.emit('error', er);
}
 
function onwriteStateUpdate(state) {
  state.writing = false;
  state.writecb = null;
  state.length -= state.writelen;
  state.writelen = 0;
}
 
function onwrite(stream, er) {
  var state = stream._writableState;
  var sync = state.sync;
  var cb = state.writecb;
 
  onwriteStateUpdate(state);
 
  if (er)
    onwriteError(stream, state, sync, er, cb);
  else {
    // Check if we're actually ready to finish, but don't emit yet
    var finished = needFinish(stream, state);
 
    if (!finished && !state.bufferProcessing && state.buffer.length)
      clearBuffer(stream, state);
 
    if (sync) {
      process.nextTick(function() {
        afterWrite(stream, state, finished, cb);
      });
    } else {
      afterWrite(stream, state, finished, cb);
    }
  }
}
 
function afterWrite(stream, state, finished, cb) {
  if (!finished)
    onwriteDrain(stream, state);
  cb();
  if (finished)
    finishMaybe(stream, state);
}
 
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
  if (state.length === 0 && state.needDrain) {
    state.needDrain = false;
    stream.emit('drain');
  }
}
 
 
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
  state.bufferProcessing = true;
 
  for (var c = 0; c < state.buffer.length; c++) {
    var entry = state.buffer[c];
    var chunk = entry.chunk;
    var encoding = entry.encoding;
    var cb = entry.callback;
    var len = state.objectMode ? 1 : chunk.length;
 
    doWrite(stream, state, len, chunk, encoding, cb);
 
    // if we didn't call the onwrite immediately, then
    // it means that we need to wait until it does.
    // also, that means that the chunk and cb are currently
    // being processed, so move the buffer counter past them.
    if (state.writing) {
      c++;
      break;
    }
  }
 
  state.bufferProcessing = false;
  if (c < state.buffer.length)
    state.buffer = state.buffer.slice(c);
  else
    state.buffer.length = 0;
}
 
Writable.prototype._write = function(chunk, encoding, cb) {
  cb(new Error('not implemented'));
};
 
Writable.prototype.end = function(chunk, encoding, cb) {
  var state = this._writableState;
 
  if (typeof chunk === 'function') {
    cb = chunk;
    chunk = null;
    encoding = null;
  } else if (typeof encoding === 'function') {
    cb = encoding;
    encoding = null;
  }
 
  if (typeof chunk !== 'undefined' && chunk !== null)
    this.write(chunk, encoding);
 
  // ignore unnecessary end() calls.
  if (!state.ending && !state.finished)
    endWritable(this, state, cb);
};
 
 
function needFinish(stream, state) {
  return (state.ending &&
          state.length === 0 &&
          !state.finished &&
          !state.writing);
}
 
function finishMaybe(stream, state) {
  var need = needFinish(stream, state);
  if (need) {
    state.finished = true;
    stream.emit('finish');
  }
  return need;
}
 
function endWritable(stream, state, cb) {
  state.ending = true;
  finishMaybe(stream, state);
  if (cb) {
    if (state.finished)
      process.nextTick(cb);
    else
      stream.once('finish', cb);
  }
  state.ended = true;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/

Statements: 65.96% (31 / 47)      Branches: 0% (0 / 15)      Functions: 0% (0 / 16)      Lines: 65.96% (31 / 47)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/
File Statements Branches Functions Lines
util.js 65.96% (31 / 47) 0% (0 / 15) 0% (0 / 16) 65.96% (31 / 47)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/core-util-is/lib/util.js

Statements: 65.96% (31 / 47)      Branches: 0% (0 / 15)      Functions: 0% (0 / 16)      Lines: 65.96% (31 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108                                              1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1     1   1       1   1     1   1               1   1     1   1      
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
 
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
  return Array.isArray(ar);
}
exports.isArray = isArray;
 
function isBoolean(arg) {
  return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
 
function isNull(arg) {
  return arg === null;
}
exports.isNull = isNull;
 
function isNullOrUndefined(arg) {
  return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
 
function isNumber(arg) {
  return typeof arg === 'number';
}
exports.isNumber = isNumber;
 
function isString(arg) {
  return typeof arg === 'string';
}
exports.isString = isString;
 
function isSymbol(arg) {
  return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
 
function isUndefined(arg) {
  return arg === void 0;
}
exports.isUndefined = isUndefined;
 
function isRegExp(re) {
  return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
 
function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
 
function isDate(d) {
  return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
 
function isError(e) {
  return isObject(e) &&
      (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
 
function isFunction(arg) {
  return typeof arg === 'function';
}
exports.isFunction = isFunction;
 
function isPrimitive(arg) {
  return arg === null ||
         typeof arg === 'boolean' ||
         typeof arg === 'number' ||
         typeof arg === 'string' ||
         typeof arg === 'symbol' ||  // ES6 symbol
         typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
 
function isBuffer(arg) {
  return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
 
function objectToString(o) {
  return Object.prototype.toString.call(o);
}
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/
File Statements Branches Functions Lines
inherits.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/inherits/inherits.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('util').inherits
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/
File Statements Branches Functions Lines
index.js 50% (1 / 2) 50% (1 / 2) 0% (0 / 1) 50% (1 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/bl/node_modules/readable-stream/node_modules/isarray/index.js

Statements: 50% (1 / 2)      Branches: 50% (1 / 2)      Functions: 0% (0 / 1)      Lines: 50% (1 / 2)      Ignored: none     

1 2 3 4 51        
module.exports = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) == '[object Array]';
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/caseless/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/caseless/

Statements: 15.69% (8 / 51)      Branches: 0% (0 / 20)      Functions: 0% (0 / 13)      Lines: 17.78% (8 / 45)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/caseless/
File Statements Branches Functions Lines
index.js 15.69% (8 / 51) 0% (0 / 20) 0% (0 / 13) 17.78% (8 / 45)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/caseless/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/caseless/index.js

Statements: 15.69% (8 / 51)      Branches: 0% (0 / 20)      Functions: 0% (0 / 13)      Lines: 17.78% (8 / 45)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671     1                           1                 1                   1           1         1 1                                    
function Caseless (dict) {
  this.dict = dict || {}
}
Caseless.prototype.set = function (name, value, clobber) {
  if (typeof name === 'object') {
    for (var i in name) {
      this.set(i, name[i], value)
    }
  } else {
    if (typeof clobber === 'undefined') clobber = true
    var has = this.has(name)
 
    if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
    else this.dict[has || name] = value
    return has
  }
}
Caseless.prototype.has = function (name) {
  var keys = Object.keys(this.dict)
    , name = name.toLowerCase()
    ;
  for (var i=0;i<keys.length;i++) {
    if (keys[i].toLowerCase() === name) return keys[i]
  }
  return false
}
Caseless.prototype.get = function (name) {
  name = name.toLowerCase()
  var result, _key
  var headers = this.dict
  Object.keys(headers).forEach(function (key) {
    _key = key.toLowerCase()
    if (name === _key) result = headers[key]
  })
  return result
}
Caseless.prototype.swap = function (name) {
  var has = this.has(name)
  if (!has) throw new Error('There is no header than matches "'+name+'"')
  this.dict[name] = this.dict[has]
  delete this.dict[has]
}
Caseless.prototype.del = function (name) {
  var has = this.has(name)
  return delete this.dict[has || name]
}
 
module.exports = function (dict) {return new Caseless(dict)}
module.exports.httpify = function (resp, headers) {
  var c = new Caseless(headers)
  resp.setHeader = function (key, value, clobber) {
    return c.set(key, value, clobber)
  }
  resp.hasHeader = function (key) {
    return c.has(key)
  }
  resp.getHeader = function (key) {
    return c.get(key)
  }
  resp.removeHeader = function (key) {
    return c.del(key)
  }
  resp.headers = c.dict
  return c
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/lib/

Statements: 19.64% (22 / 112)      Branches: 0% (0 / 43)      Functions: 0% (0 / 20)      Lines: 20% (22 / 110)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/lib/
File Statements Branches Functions Lines
combined_stream.js 19.64% (22 / 112) 0% (0 / 43) 0% (0 / 20) 20% (22 / 110)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/lib/combined_stream.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/lib/combined_stream.js

Statements: 19.64% (22 / 112)      Branches: 0% (0 / 43)      Functions: 0% (0 / 20)      Lines: 20% (22 / 110)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 1901 1 1   1 1                     1   1                     1               1                                               1           1                                                     1                             1             1       1                 1                     1         1         1           1                     1                                 1          
var util = require('util');
var Stream = require('stream').Stream;
var DelayedStream = require('delayed-stream');
 
module.exports = CombinedStream;
function CombinedStream() {
  this.writable = false;
  this.readable = true;
  this.dataSize = 0;
  this.maxDataSize = 2 * 1024 * 1024;
  this.pauseStreams = true;
 
  this._released = false;
  this._streams = [];
  this._currentStream = null;
}
util.inherits(CombinedStream, Stream);
 
CombinedStream.create = function(options) {
  var combinedStream = new this();
 
  options = options || {};
  for (var option in options) {
    combinedStream[option] = options[option];
  }
 
  return combinedStream;
};
 
CombinedStream.isStreamLike = function(stream) {
  return (typeof stream !== 'function')
    && (typeof stream !== 'string')
    && (typeof stream !== 'boolean')
    && (typeof stream !== 'number')
    && (!Buffer.isBuffer(stream));
};
 
CombinedStream.prototype.append = function(stream) {
  var isStreamLike = CombinedStream.isStreamLike(stream);
 
  if (isStreamLike) {
    if (!(stream instanceof DelayedStream)) {
      var newStream = DelayedStream.create(stream, {
        maxDataSize: Infinity,
        pauseStream: this.pauseStreams,
      });
      stream.on('data', this._checkDataSize.bind(this));
      stream = newStream;
    }
 
    this._handleErrors(stream);
 
    if (this.pauseStreams) {
      stream.pause();
    }
  }
 
  this._streams.push(stream);
  return this;
};
 
CombinedStream.prototype.pipe = function(dest, options) {
  Stream.prototype.pipe.call(this, dest, options);
  this.resume();
  return dest;
};
 
CombinedStream.prototype._getNext = function() {
  this._currentStream = null;
  var stream = this._streams.shift();
 
 
  if (typeof stream == 'undefined') {
    this.end();
    return;
  }
 
  if (typeof stream !== 'function') {
    this._pipeNext(stream);
    return;
  }
 
  var getStream = stream;
  getStream(function(stream) {
    var isStreamLike = CombinedStream.isStreamLike(stream);
    if (isStreamLike) {
      stream.on('data', this._checkDataSize.bind(this));
      this._handleErrors(stream);
    }
 
    this._pipeNext(stream);
  }.bind(this));
};
 
CombinedStream.prototype._pipeNext = function(stream) {
  this._currentStream = stream;
 
  var isStreamLike = CombinedStream.isStreamLike(stream);
  if (isStreamLike) {
    stream.on('end', this._getNext.bind(this));
    stream.pipe(this, {end: false});
    return;
  }
 
  var value = stream;
  this.write(value);
  this._getNext();
};
 
CombinedStream.prototype._handleErrors = function(stream) {
  var self = this;
  stream.on('error', function(err) {
    self._emitError(err);
  });
};
 
CombinedStream.prototype.write = function(data) {
  this.emit('data', data);
};
 
CombinedStream.prototype.pause = function() {
  if (!this.pauseStreams) {
    return;
  }
 
  if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
  this.emit('pause');
};
 
CombinedStream.prototype.resume = function() {
  if (!this._released) {
    this._released = true;
    this.writable = true;
    this._getNext();
  }
 
  if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
  this.emit('resume');
};
 
CombinedStream.prototype.end = function() {
  this._reset();
  this.emit('end');
};
 
CombinedStream.prototype.destroy = function() {
  this._reset();
  this.emit('close');
};
 
CombinedStream.prototype._reset = function() {
  this.writable = false;
  this._streams = [];
  this._currentStream = null;
};
 
CombinedStream.prototype._checkDataSize = function() {
  this._updateDataSize();
  if (this.dataSize <= this.maxDataSize) {
    return;
  }
 
  var message =
    'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
  this._emitError(new Error(message));
};
 
CombinedStream.prototype._updateDataSize = function() {
  this.dataSize = 0;
 
  var self = this;
  this._streams.forEach(function(stream) {
    if (!stream.dataSize) {
      return;
    }
 
    self.dataSize += stream.dataSize;
  });
 
  if (this._currentStream && this._currentStream.dataSize) {
    this.dataSize += this._currentStream.dataSize;
  }
};
 
CombinedStream.prototype._emitError = function(err) {
  this._reset();
  this.emit('error', err);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/

Statements: 22.95% (14 / 61)      Branches: 0% (0 / 14)      Functions: 0% (0 / 13)      Lines: 22.95% (14 / 61)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/
File Statements Branches Functions Lines
delayed_stream.js 22.95% (14 / 61) 0% (0 / 14) 0% (0 / 13) 22.95% (14 / 61)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js

Statements: 22.95% (14 / 61)      Branches: 0% (0 / 14)      Functions: 0% (0 / 13)      Lines: 22.95% (14 / 61)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 1091 1   1 1                   1   1                                               1               1       1               1       1                 1           1                           1                              
var Stream = require('stream').Stream;
var util = require('util');
 
module.exports = DelayedStream;
function DelayedStream() {
  this.source = null;
  this.dataSize = 0;
  this.maxDataSize = 1024 * 1024;
  this.pauseStream = true;
 
  this._maxDataSizeExceeded = false;
  this._released = false;
  this._bufferedEvents = [];
}
util.inherits(DelayedStream, Stream);
 
DelayedStream.create = function(source, options) {
  var delayedStream = new this();
 
  options = options || {};
  for (var option in options) {
    delayedStream[option] = options[option];
  }
 
  delayedStream.source = source;
 
  var realEmit = source.emit;
  source.emit = function() {
    delayedStream._handleEmit(arguments);
    return realEmit.apply(source, arguments);
  };
 
  source.on('error', function() {});
  if (delayedStream.pauseStream) {
    source.pause();
  }
 
  return delayedStream;
};
 
Object.defineProperty(DelayedStream.prototype, 'readable', {
  configurable: true,
  enumerable: true,
  get: function() {
    return this.source.readable;
  }
});
 
DelayedStream.prototype.setEncoding = function() {
  return this.source.setEncoding.apply(this.source, arguments);
};
 
DelayedStream.prototype.resume = function() {
  if (!this._released) {
    this.release();
  }
 
  this.source.resume();
};
 
DelayedStream.prototype.pause = function() {
  this.source.pause();
};
 
DelayedStream.prototype.release = function() {
  this._released = true;
 
  this._bufferedEvents.forEach(function(args) {
    this.emit.apply(this, args);
  }.bind(this));
  this._bufferedEvents = [];
};
 
DelayedStream.prototype.pipe = function() {
  var r = Stream.prototype.pipe.apply(this, arguments);
  this.resume();
  return r;
};
 
DelayedStream.prototype._handleEmit = function(args) {
  if (this._released) {
    this.emit.apply(this, args);
    return;
  }
 
  if (args[0] === 'data') {
    this.dataSize += args[1].length;
    this._checkIfMaxDataSizeExceeded();
  }
 
  this._bufferedEvents.push(args);
};
 
DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
  if (this._maxDataSizeExceeded) {
    return;
  }
 
  if (this.dataSize <= this.maxDataSize) {
    return;
  }
 
  this._maxDataSizeExceeded = true;
  var message =
    'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
  this.emit('error', new Error(message));
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/forever-agent/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/forever-agent/

Statements: 19.75% (16 / 81)      Branches: 0% (0 / 53)      Functions: 0% (0 / 8)      Lines: 20% (16 / 80)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/forever-agent/
File Statements Branches Functions Lines
index.js 19.75% (16 / 81) 0% (0 / 53) 0% (0 / 8) 20% (16 / 80)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/forever-agent/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/forever-agent/index.js

Statements: 19.75% (16 / 81)      Branches: 0% (0 / 53)      Functions: 0% (0 / 8)      Lines: 20% (16 / 80)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 1401 1   1           1                     1                                                                 1   1     1 1 1                                       1                                                         1     1   1 1   1                                            
module.exports = ForeverAgent
ForeverAgent.SSL = ForeverAgentSSL
 
var util = require('util')
  , Agent = require('http').Agent
  , net = require('net')
  , tls = require('tls')
  , AgentSSL = require('https').Agent
  
function getConnectionName(host, port) {  
  var name = ''
  if (typeof host === 'string') {
    name = host + ':' + port
  } else {
    // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
    name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':')
  }
  return name
}    
 
function ForeverAgent(options) {
  var self = this
  self.options = options || {}
  self.requests = {}
  self.sockets = {}
  self.freeSockets = {}
  self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
  self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
  self.on('free', function(socket, host, port) {
    var name = getConnectionName(host, port)
 
    if (self.requests[name] && self.requests[name].length) {
      self.requests[name].shift().onSocket(socket)
    } else if (self.sockets[name].length < self.minSockets) {
      if (!self.freeSockets[name]) self.freeSockets[name] = []
      self.freeSockets[name].push(socket)
      
      // if an error happens while we don't use the socket anyway, meh, throw the socket away
      var onIdleError = function() {
        socket.destroy()
      }
      socket._onIdleError = onIdleError
      socket.on('error', onIdleError)
    } else {
      // If there are no pending requests just destroy the
      // socket and it will get removed from the pool. This
      // gets us out of timeout issues and allows us to
      // default to Connection:keep-alive.
      socket.destroy()
    }
  })
 
}
util.inherits(ForeverAgent, Agent)
 
ForeverAgent.defaultMinSockets = 5
 
 
ForeverAgent.prototype.createConnection = net.createConnection
ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
ForeverAgent.prototype.addRequest = function(req, host, port) {
  var name = getConnectionName(host, port)
  
  if (typeof host !== 'string') {
    var options = host
    port = options.port
    host = options.host
  }
 
  if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
    var idleSocket = this.freeSockets[name].pop()
    idleSocket.removeListener('error', idleSocket._onIdleError)
    delete idleSocket._onIdleError
    req._reusedSocket = true
    req.onSocket(idleSocket)
  } else {
    this.addRequestNoreuse(req, host, port)
  }
}
 
ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
  if (this.sockets[name]) {
    var index = this.sockets[name].indexOf(s)
    if (index !== -1) {
      this.sockets[name].splice(index, 1)
    }
  } else if (this.sockets[name] && this.sockets[name].length === 0) {
    // don't leak
    delete this.sockets[name]
    delete this.requests[name]
  }
  
  if (this.freeSockets[name]) {
    var index = this.freeSockets[name].indexOf(s)
    if (index !== -1) {
      this.freeSockets[name].splice(index, 1)
      if (this.freeSockets[name].length === 0) {
        delete this.freeSockets[name]
      }
    }
  }
 
  if (this.requests[name] && this.requests[name].length) {
    // If we have pending requests and a socket gets closed a new one
    // needs to be created to take over in the pool for the one that closed.
    this.createSocket(name, host, port).emit('free')
  }
}
 
function ForeverAgentSSL (options) {
  ForeverAgent.call(this, options)
}
util.inherits(ForeverAgentSSL, ForeverAgent)
 
ForeverAgentSSL.prototype.createConnection = createConnectionSSL
ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
 
function createConnectionSSL (port, host, options) {
  if (typeof port === 'object') {
    options = port;
  } else if (typeof host === 'object') {
    options = host;
  } else if (typeof options === 'object') {
    options = options;
  } else {
    options = {};
  }
 
  if (typeof port === 'number') {
    options.port = port;
  }
 
  if (typeof host === 'string') {
    options.host = host;
  }
 
  return tls.connect(options);
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/lib/

Statements: 17.65% (27 / 153)      Branches: 0% (0 / 84)      Functions: 0% (0 / 22)      Lines: 18% (27 / 150)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/lib/
File Statements Branches Functions Lines
form_data.js 17.65% (27 / 153) 0% (0 / 84) 0% (0 / 22) 18% (27 / 150)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/lib/form_data.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/lib/form_data.js

Statements: 17.65% (27 / 153)      Branches: 0% (0 / 84)      Functions: 0% (0 / 22)      Lines: 18% (27 / 150)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 3531 1 1 1 1 1 1 1 1   1 1             1   1   1                                                     1                                                                                                                                                                         1                                                                   1                         1       1                       1                     1               1                           1                                       1                                                   1                                                                                                               1                         1              
var CombinedStream = require('combined-stream');
var util = require('util');
var path = require('path');
var http = require('http');
var https = require('https');
var parseUrl = require('url').parse;
var fs = require('fs');
var mime = require('mime-types');
var async = require('async');
 
module.exports = FormData;
function FormData() {
  this._overheadLength = 0;
  this._valueLength = 0;
  this._lengthRetrievers = [];
 
  CombinedStream.call(this);
}
util.inherits(FormData, CombinedStream);
 
FormData.LINE_BREAK = '\r\n';
 
FormData.prototype.append = function(field, value, options) {
  options = options || {};
 
  var append = CombinedStream.prototype.append.bind(this);
 
  // all that streamy business can't handle numbers
  if (typeof value == 'number') value = ''+value;
 
  // https://github.com/felixge/node-form-data/issues/38
  if (util.isArray(value)) {
    // Please convert your array into string
    // the way web server expects it
    this._error(new Error('Arrays are not supported.'));
    return;
  }
 
  var header = this._multiPartHeader(field, value, options);
  var footer = this._multiPartFooter(field, value, options);
 
  append(header);
  append(value);
  append(footer);
 
  // pass along options.knownLength
  this._trackLength(header, value, options);
};
 
FormData.prototype._trackLength = function(header, value, options) {
  var valueLength = 0;
 
  // used w/ getLengthSync(), when length is known.
  // e.g. for streaming directly from a remote server,
  // w/ a known file a size, and not wanting to wait for
  // incoming file to finish to get its size.
  if (options.knownLength != null) {
    valueLength += +options.knownLength;
  } else if (Buffer.isBuffer(value)) {
    valueLength = value.length;
  } else if (typeof value === 'string') {
    valueLength = Buffer.byteLength(value);
  }
 
  this._valueLength += valueLength;
 
  // @check why add CRLF? does this account for custom/multiple CRLFs?
  this._overheadLength +=
    Buffer.byteLength(header) +
    + FormData.LINE_BREAK.length;
 
  // empty or either doesn't have path or not an http response
  if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) {
    return;
  }
 
  // no need to bother with the length
  if (!options.knownLength)
  this._lengthRetrievers.push(function(next) {
 
    if (value.hasOwnProperty('fd')) {
 
      // take read range into a account
      // `end` = Infinity –> read file till the end
      //
      // TODO: Looks like there is bug in Node fs.createReadStream
      // it doesn't respect `end` options without `start` options
      // Fix it when node fixes it.
      // https://github.com/joyent/node/issues/7819
      if (value.end != undefined && value.end != Infinity && value.start != undefined) {
 
        // when end specified
        // no need to calculate range
        // inclusive, starts with 0
        next(null, value.end+1 - (value.start ? value.start : 0));
 
      // not that fast snoopy
      } else {
        // still need to fetch file size from fs
        fs.stat(value.path, function(err, stat) {
 
          var fileSize;
 
          if (err) {
            next(err);
            return;
          }
 
          // update final size based on the range options
          fileSize = stat.size - (value.start ? value.start : 0);
          next(null, fileSize);
        });
      }
 
    // or http response
    } else if (value.hasOwnProperty('httpVersion')) {
      next(null, +value.headers['content-length']);
 
    // or request stream http://github.com/mikeal/request
    } else if (value.hasOwnProperty('httpModule')) {
      // wait till response come back
      value.on('response', function(response) {
        value.pause();
        next(null, +response.headers['content-length']);
      });
      value.resume();
 
    // something else
    } else {
      next('Unknown stream');
    }
  });
};
 
FormData.prototype._multiPartHeader = function(field, value, options) {
  var boundary = this.getBoundary();
  var header = '';
 
  // custom header specified (as string)?
  // it becomes responsible for boundary
  // (e.g. to handle extra CRLFs on .NET servers)
  if (options.header != null) {
    header = options.header;
  } else {
    header += '--' + boundary + FormData.LINE_BREAK +
      'Content-Disposition: form-data; name="' + field + '"';
 
    // fs- and request- streams have path property
    // or use custom filename and/or contentType
    // TODO: Use request's response mime-type
    if (options.filename || value.path) {
      header +=
        '; filename="' + path.basename(options.filename || value.path) + '"' + FormData.LINE_BREAK +
        'Content-Type: ' +  (options.contentType || mime.lookup(options.filename || value.path));
 
    // http response has not
    } else if (value.readable && value.hasOwnProperty('httpVersion')) {
      header +=
        '; filename="' + path.basename(value.client._httpMessage.path) + '"' + FormData.LINE_BREAK +
        'Content-Type: ' + value.headers['content-type'];
    }
 
    header += FormData.LINE_BREAK + FormData.LINE_BREAK;
  }
 
  return header;
};
 
FormData.prototype._multiPartFooter = function(field, value, options) {
  return function(next) {
    var footer = FormData.LINE_BREAK;
 
    var lastPart = (this._streams.length === 0);
    if (lastPart) {
      footer += this._lastBoundary();
    }
 
    next(footer);
  }.bind(this);
};
 
FormData.prototype._lastBoundary = function() {
  return '--' + this.getBoundary() + '--';
};
 
FormData.prototype.getHeaders = function(userHeaders) {
  var formHeaders = {
    'content-type': 'multipart/form-data; boundary=' + this.getBoundary()
  };
 
  for (var header in userHeaders) {
    formHeaders[header.toLowerCase()] = userHeaders[header];
  }
 
  return formHeaders;
}
 
FormData.prototype.getCustomHeaders = function(contentType) {
    contentType = contentType ? contentType : 'multipart/form-data';
 
    var formHeaders = {
        'content-type': contentType + '; boundary=' + this.getBoundary(),
        'content-length': this.getLengthSync()
    };
 
    return formHeaders;
}
 
FormData.prototype.getBoundary = function() {
  if (!this._boundary) {
    this._generateBoundary();
  }
 
  return this._boundary;
};
 
FormData.prototype._generateBoundary = function() {
  // This generates a 50 character boundary similar to those used by Firefox.
  // They are optimized for boyer-moore parsing.
  var boundary = '--------------------------';
  for (var i = 0; i < 24; i++) {
    boundary += Math.floor(Math.random() * 10).toString(16);
  }
 
  this._boundary = boundary;
};
 
// Note: getLengthSync DOESN'T calculate streams length
// As workaround one can calculate file size manually
// and add it as knownLength option
FormData.prototype.getLengthSync = function(debug) {
  var knownLength = this._overheadLength + this._valueLength;
 
  // Don't get confused, there are 3 "internal" streams for each keyval pair
  // so it basically checks if there is any value added to the form
  if (this._streams.length) {
    knownLength += this._lastBoundary().length;
  }
 
  // https://github.com/felixge/node-form-data/issues/40
  if (this._lengthRetrievers.length) {
    // Some async length retrivers are present
    // therefore synchronous length calculation is false.
    // Please use getLength(callback) to get proper length
    this._error(new Error('Cannot calculate proper length in synchronous way.'));
  }
 
  return knownLength;
};
 
FormData.prototype.getLength = function(cb) {
  var knownLength = this._overheadLength + this._valueLength;
 
  if (this._streams.length) {
    knownLength += this._lastBoundary().length;
  }
 
  if (!this._lengthRetrievers.length) {
    process.nextTick(cb.bind(this, null, knownLength));
    return;
  }
 
  async.parallel(this._lengthRetrievers, function(err, values) {
    if (err) {
      cb(err);
      return;
    }
 
    values.forEach(function(length) {
      knownLength += length;
    });
 
    cb(null, knownLength);
  });
};
 
FormData.prototype.submit = function(params, cb) {
 
  var request
    , options
    , defaults = {
        method : 'post'
    };
 
  // parse provided url if it's string
  // or treat it as options object
  if (typeof params == 'string') {
    params = parseUrl(params);
 
    options = populate({
      port: params.port,
      path: params.pathname,
      host: params.hostname
    }, defaults);
  }
  else // use custom params
  {
    options = populate(params, defaults);
    // if no port provided use default one
    if (!options.port) {
      options.port = options.protocol == 'https:' ? 443 : 80;
    }
  }
 
  // put that good code in getHeaders to some use
  options.headers = this.getHeaders(params.headers);
 
  // https if specified, fallback to http in any other case
  if (params.protocol == 'https:') {
    request = https.request(options);
  } else {
    request = http.request(options);
  }
 
  // get content length and fire away
  this.getLength(function(err, length) {
 
    // TODO: Add chunked encoding when no length (if err)
 
    // add content length
    request.setHeader('Content-Length', length);
 
    this.pipe(request);
    if (cb) {
      request.on('error', cb);
      request.on('response', cb.bind(this, null));
    }
  }.bind(this));
 
  return request;
};
 
FormData.prototype._error = function(err) {
  if (this.error) return;
 
  this.error = err;
  this.pause();
  this.emit('error', err);
};
 
/*
 * Santa's little helpers
 */
 
// populates missing values
function populate(dst, src) {
  for (var prop in src) {
    if (!dst[prop]) dst[prop] = src[prop];
  }
  return dst;
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/

Statements: 19.64% (22 / 112)      Branches: 0% (0 / 43)      Functions: 0% (0 / 20)      Lines: 20% (22 / 110)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/
File Statements Branches Functions Lines
combined_stream.js 19.64% (22 / 112) 0% (0 / 43) 0% (0 / 20) 20% (22 / 110)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/lib/combined_stream.js

Statements: 19.64% (22 / 112)      Branches: 0% (0 / 43)      Functions: 0% (0 / 20)      Lines: 20% (22 / 110)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 1901 1 1   1 1                     1   1                     1               1                                               1           1                                                     1                             1             1       1                 1                     1         1         1           1                     1                                 1          
var util = require('util');
var Stream = require('stream').Stream;
var DelayedStream = require('delayed-stream');
 
module.exports = CombinedStream;
function CombinedStream() {
  this.writable = false;
  this.readable = true;
  this.dataSize = 0;
  this.maxDataSize = 2 * 1024 * 1024;
  this.pauseStreams = true;
 
  this._released = false;
  this._streams = [];
  this._currentStream = null;
}
util.inherits(CombinedStream, Stream);
 
CombinedStream.create = function(options) {
  var combinedStream = new this();
 
  options = options || {};
  for (var option in options) {
    combinedStream[option] = options[option];
  }
 
  return combinedStream;
};
 
CombinedStream.isStreamLike = function(stream) {
  return (typeof stream !== 'function')
    && (typeof stream !== 'string')
    && (typeof stream !== 'boolean')
    && (typeof stream !== 'number')
    && (!Buffer.isBuffer(stream));
};
 
CombinedStream.prototype.append = function(stream) {
  var isStreamLike = CombinedStream.isStreamLike(stream);
 
  if (isStreamLike) {
    if (!(stream instanceof DelayedStream)) {
      var newStream = DelayedStream.create(stream, {
        maxDataSize: Infinity,
        pauseStream: this.pauseStreams,
      });
      stream.on('data', this._checkDataSize.bind(this));
      stream = newStream;
    }
 
    this._handleErrors(stream);
 
    if (this.pauseStreams) {
      stream.pause();
    }
  }
 
  this._streams.push(stream);
  return this;
};
 
CombinedStream.prototype.pipe = function(dest, options) {
  Stream.prototype.pipe.call(this, dest, options);
  this.resume();
  return dest;
};
 
CombinedStream.prototype._getNext = function() {
  this._currentStream = null;
  var stream = this._streams.shift();
 
 
  if (typeof stream == 'undefined') {
    this.end();
    return;
  }
 
  if (typeof stream !== 'function') {
    this._pipeNext(stream);
    return;
  }
 
  var getStream = stream;
  getStream(function(stream) {
    var isStreamLike = CombinedStream.isStreamLike(stream);
    if (isStreamLike) {
      stream.on('data', this._checkDataSize.bind(this));
      this._handleErrors(stream);
    }
 
    this._pipeNext(stream);
  }.bind(this));
};
 
CombinedStream.prototype._pipeNext = function(stream) {
  this._currentStream = stream;
 
  var isStreamLike = CombinedStream.isStreamLike(stream);
  if (isStreamLike) {
    stream.on('end', this._getNext.bind(this));
    stream.pipe(this, {end: false});
    return;
  }
 
  var value = stream;
  this.write(value);
  this._getNext();
};
 
CombinedStream.prototype._handleErrors = function(stream) {
  var self = this;
  stream.on('error', function(err) {
    self._emitError(err);
  });
};
 
CombinedStream.prototype.write = function(data) {
  this.emit('data', data);
};
 
CombinedStream.prototype.pause = function() {
  if (!this.pauseStreams) {
    return;
  }
 
  if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
  this.emit('pause');
};
 
CombinedStream.prototype.resume = function() {
  if (!this._released) {
    this._released = true;
    this.writable = true;
    this._getNext();
  }
 
  if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
  this.emit('resume');
};
 
CombinedStream.prototype.end = function() {
  this._reset();
  this.emit('end');
};
 
CombinedStream.prototype.destroy = function() {
  this._reset();
  this.emit('close');
};
 
CombinedStream.prototype._reset = function() {
  this.writable = false;
  this._streams = [];
  this._currentStream = null;
};
 
CombinedStream.prototype._checkDataSize = function() {
  this._updateDataSize();
  if (this.dataSize <= this.maxDataSize) {
    return;
  }
 
  var message =
    'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
  this._emitError(new Error(message));
};
 
CombinedStream.prototype._updateDataSize = function() {
  this.dataSize = 0;
 
  var self = this;
  this._streams.forEach(function(stream) {
    if (!stream.dataSize) {
      return;
    }
 
    self.dataSize += stream.dataSize;
  });
 
  if (this._currentStream && this._currentStream.dataSize) {
    this.dataSize += this._currentStream.dataSize;
  }
};
 
CombinedStream.prototype._emitError = function(err) {
  this._reset();
  this.emit('error', err);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/

Statements: 22.03% (13 / 59)      Branches: 0% (0 / 14)      Functions: 0% (0 / 12)      Lines: 22.03% (13 / 59)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/
File Statements Branches Functions Lines
delayed_stream.js 22.03% (13 / 59) 0% (0 / 14) 0% (0 / 12) 22.03% (13 / 59)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/form-data/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js

Statements: 22.03% (13 / 59)      Branches: 0% (0 / 14)      Functions: 0% (0 / 12)      Lines: 22.03% (13 / 59)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 1011 1   1 1                   1   1                                               1       1               1       1                 1           1                           1                              
var Stream = require('stream').Stream;
var util = require('util');
 
module.exports = DelayedStream;
function DelayedStream() {
  this.source = null;
  this.dataSize = 0;
  this.maxDataSize = 1024 * 1024;
  this.pauseStream = true;
 
  this._maxDataSizeExceeded = false;
  this._released = false;
  this._bufferedEvents = [];
}
util.inherits(DelayedStream, Stream);
 
DelayedStream.create = function(source, options) {
  var delayedStream = new this();
 
  options = options || {};
  for (var option in options) {
    delayedStream[option] = options[option];
  }
 
  delayedStream.source = source;
 
  var realEmit = source.emit;
  source.emit = function() {
    delayedStream._handleEmit(arguments);
    return realEmit.apply(source, arguments);
  };
 
  source.on('error', function() {});
  if (delayedStream.pauseStream) {
    source.pause();
  }
 
  return delayedStream;
};
 
DelayedStream.prototype.__defineGetter__('readable', function() {
  return this.source.readable;
});
 
DelayedStream.prototype.resume = function() {
  if (!this._released) {
    this.release();
  }
 
  this.source.resume();
};
 
DelayedStream.prototype.pause = function() {
  this.source.pause();
};
 
DelayedStream.prototype.release = function() {
  this._released = true;
 
  this._bufferedEvents.forEach(function(args) {
    this.emit.apply(this, args);
  }.bind(this));
  this._bufferedEvents = [];
};
 
DelayedStream.prototype.pipe = function() {
  var r = Stream.prototype.pipe.apply(this, arguments);
  this.resume();
  return r;
};
 
DelayedStream.prototype._handleEmit = function(args) {
  if (this._released) {
    this.emit.apply(this, args);
    return;
  }
 
  if (args[0] === 'data') {
    this.dataSize += args[1].length;
    this._checkIfMaxDataSizeExceeded();
  }
 
  this._bufferedEvents.push(args);
};
 
DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
  if (this._maxDataSizeExceeded) {
    return;
  }
 
  if (this.dataSize <= this.maxDataSize) {
    return;
  }
 
  this._maxDataSizeExceeded = true;
  var message =
    'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
  this.emit('error', new Error(message));
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/

Statements: 8.77% (35 / 399)      Branches: 0% (0 / 237)      Functions: 0% (0 / 44)      Lines: 9.83% (35 / 356)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/
File Statements Branches Functions Lines
formats.js 100% (14 / 14) 100% (0 / 0) 100% (0 / 0) 100% (14 / 14)
index.js 5.45% (21 / 385) 0% (0 / 237) 0% (0 / 44) 6.14% (21 / 342)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/formats.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/formats.js

Statements: 100% (14 / 14)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (14 / 14)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 1 1 1 1 1 1 1 1 1 1 1 1 1    
exports['date-time'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}[tT ]\d{2}:\d{2}:\d{2}(\.\d+)?([zZ]|[+-]\d{2}:\d{2})$/
exports['date'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/
exports['time'] = /^\d{2}:\d{2}:\d{2}$/
exports['email'] = /^\S+@\S+$/
exports['ip-address'] = exports['ipv4'] = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
exports['ipv6'] = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
exports['uri'] = /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/
exports['color'] = /(#?([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))/
exports['hostname'] = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/
exports['alpha'] = /^[a-zA-Z]+$/
exports['alphanumeric'] = /^[a-zA-Z0-9]+$/
exports['style'] = /\s*(.+?):\s*([^;]+);?/g
exports['phone'] = /^\+(?:[0-9] ?){6,14}[0-9]$/
exports['utc-millisec'] = /^[0-9]+(\.?[0-9]+)?$/
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/index.js

Statements: 5.45% (21 / 385)      Branches: 0% (0 / 237)      Functions: 0% (0 / 44)      Lines: 6.14% (21 / 342)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 5711 1 1 1 1   1                                                                                   1             1   1       1       1       1       1       1       1       1       1                     1       1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         1         1                
var genobj = require('generate-object-property')
var genfun = require('generate-function')
var jsonpointer = require('jsonpointer')
var xtend = require('xtend')
var formats = require('./formats')
 
var get = function(obj, additionalSchemas, ptr) {
  if (/^https?:\/\//.test(ptr)) return null
 
  var visit = function(sub) {
    if (sub && sub.id === ptr) return sub
    if (typeof sub !== 'object' || !sub) return null
    return Object.keys(sub).reduce(function(res, k) {
      return res || visit(sub[k])
    }, null)
  }
 
  var res = visit(obj)
  if (res) return res
 
  ptr = ptr.replace(/^#/, '')
  ptr = ptr.replace(/\/$/, '')
 
  try {
    return jsonpointer.get(obj, decodeURI(ptr))
  } catch (err) {
    var end = ptr.indexOf('#')
    var other
    // external reference
    if (end !== 0) {
      // fragment doesn't exist.
      if (end === -1) {
        other = additionalSchemas[ptr]
      } else {
        var ext = ptr.slice(0, end)
        other = additionalSchemas[ext]
        var fragment = ptr.slice(end).replace(/^#/, '')
        try {
          return jsonpointer.get(other, fragment)
        } catch (err) {}
      }
    } else {
      other = additionalSchemas[ptr]
    }
    return other || null
  }
}
 
var formatName = function(field) {
  field = JSON.stringify(field)
  var pattern = /\[([^\[\]"]+)\]/
  while (pattern.test(field)) field = field.replace(pattern, '."+$1+"')
  return field
}
 
var types = {}
 
types.any = function() {
  return 'true'
}
 
types.null = function(name) {
  return name+' === null'
}
 
types.boolean = function(name) {
  return 'typeof '+name+' === "boolean"'
}
 
types.array = function(name) {
  return 'Array.isArray('+name+')'
}
 
types.object = function(name) {
  return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')'
}
 
types.number = function(name) {
  return 'typeof '+name+' === "number"'
}
 
types.integer = function(name) {
  return 'typeof '+name+' === "number" && (Math.floor('+name+') === '+name+' || '+name+' > 9007199254740992 || '+name+' < -9007199254740992)'
}
 
types.string = function(name) {
  return 'typeof '+name+' === "string"'
}
 
var unique = function(array) {
  var list = []
  for (var i = 0; i < array.length; i++) {
    list.push(typeof array[i] === 'object' ? JSON.stringify(array[i]) : array[i])
  }
  for (var i = 1; i < list.length; i++) {
    if (list.indexOf(list[i]) !== i) return false
  }
  return true
}
 
var toType = function(node) {
  return node.type
}
 
var compile = function(schema, cache, root, reporter, opts) {
  var fmts = opts ? xtend(formats, opts.formats) : formats
  var scope = {unique:unique, formats:fmts}
  var verbose = opts ? !!opts.verbose : false;
  var greedy = opts && opts.greedy !== undefined ?
    opts.greedy : false;
 
  var syms = {}
  var gensym = function(name) {
    return name+(syms[name] = (syms[name] || 0)+1)
  }
 
  var reversePatterns = {}
  var patterns = function(p) {
    if (reversePatterns[p]) return reversePatterns[p]
    var n = gensym('pattern')
    scope[n] = new RegExp(p)
    reversePatterns[p] = n
    return n
  }
 
  var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
  var genloop = function() {
    var v = vars.shift()
    vars.push(v+v[0])
    return v
  }
 
  var visit = function(name, node, reporter, filter) {
    var properties = node.properties
    var type = node.type
    var tuple = false
 
    if (Array.isArray(node.items)) { // tuple type
      properties = {}
      node.items.forEach(function(item, i) {
        properties[i] = item
      })
      type = 'array'
      tuple = true
    }
 
    var indent = 0
    var error = function(msg, prop, value) {
      validate('errors++')
      if (reporter === true) {
        validate('if (validate.errors === null) validate.errors = []')
        if (verbose) {
          validate('validate.errors.push({field:%s,message:%s,value:%s})', formatName(prop || name), JSON.stringify(msg), value || name)
        } else {
          validate('validate.errors.push({field:%s,message:%s})', formatName(prop || name), JSON.stringify(msg))
        }
      }
    }
 
    if (node.required === true) {
      indent++
      validate('if (%s === undefined) {', name)
      error('is required')
      validate('} else {')
    } else {
      indent++
      validate('if (%s !== undefined) {', name)
    }
 
    var valid = [].concat(type)
      .map(function(t) {
        return types[t || 'any'](name)
      })
      .join(' || ') || 'true'
 
    if (valid !== 'true') {
      indent++
      validate('if (!(%s)) {', valid)
      error('is the wrong type')
      validate('} else {')
    }
 
    if (tuple) {
      if (node.additionalItems === false) {
        validate('if (%s.length > %d) {', name, node.items.length)
        error('has additional items')
        validate('}')
      } else if (node.additionalItems) {
        var i = genloop()
        validate('for (var %s = %d; %s < %s.length; %s++) {', i, node.items.length, i, name, i)
        visit(name+'['+i+']', node.additionalItems, reporter, filter)
        validate('}')
      }   
    }
 
    if (node.format && fmts[node.format]) {
      if (type !== 'string' && formats[node.format]) validate('if (%s) {', types.string(name))
      var n = gensym('format')
      scope[n] = fmts[node.format]
 
      if (typeof scope[n] === 'function') validate('if (!%s(%s)) {', n, name)
      else validate('if (!%s.test(%s)) {', n, name)
      error('must be '+node.format+' format')
      validate('}')
      if (type !== 'string' && formats[node.format]) validate('}')
    }
 
    if (Array.isArray(node.required)) {
      var isUndefined = function(req) {
        return genobj(name, req) + ' === undefined'
      }
 
      var checkRequired = function (req) {
        var prop = genobj(name, req);
        validate('if (%s === undefined) {', prop)
        error('is required', prop)
        validate('missing++')
        validate('}')
      }
      validate('if ((%s)) {', type !== 'object' ? types.object(name) : 'true')
      validate('var missing = 0')
      node.required.map(checkRequired)
      validate('}');
      if (!greedy) {
        validate('if (missing === 0) {')
        indent++
      }
    }
 
    if (node.uniqueItems) {
      if (type !== 'array') validate('if (%s) {', types.array(name))
      validate('if (!(unique(%s))) {', name)
      error('must be unique')
      validate('}')
      if (type !== 'array') validate('}')
    }
 
    if (node.enum) {
      var complex = node.enum.some(function(e) {
        return typeof e === 'object'
      })
 
      var compare = complex ?
        function(e) {
          return 'JSON.stringify('+name+')'+' !== JSON.stringify('+JSON.stringify(e)+')'
        } :
        function(e) {
          return name+' !== '+JSON.stringify(e)
        }
 
      validate('if (%s) {', node.enum.map(compare).join(' && ') || 'false')
      error('must be an enum value')
      validate('}')
    }
 
    if (node.dependencies) {
      if (type !== 'object') validate('if (%s) {', types.object(name))
 
      Object.keys(node.dependencies).forEach(function(key) {
        var deps = node.dependencies[key]
        if (typeof deps === 'string') deps = [deps]
 
        var exists = function(k) {
          return genobj(name, k) + ' !== undefined'
        }
 
        if (Array.isArray(deps)) {
          validate('if (%s !== undefined && !(%s)) {', genobj(name, key), deps.map(exists).join(' && ') || 'true')
          error('dependencies not set')
          validate('}')
        }
        if (typeof deps === 'object') {
          validate('if (%s !== undefined) {', genobj(name, key))
          visit(name, deps, reporter, filter)
          validate('}')
        }
      })
 
      if (type !== 'object') validate('}')
    }
 
    if (node.additionalProperties || node.additionalProperties === false) {
      if (type !== 'object') validate('if (%s) {', types.object(name))
 
      var i = genloop()
      var keys = gensym('keys')
 
      var toCompare = function(p) {
        return keys+'['+i+'] !== '+JSON.stringify(p)
      }
 
      var toTest = function(p) {
        return '!'+patterns(p)+'.test('+keys+'['+i+'])'
      }
 
      var additionalProp = Object.keys(properties || {}).map(toCompare)
        .concat(Object.keys(node.patternProperties || {}).map(toTest))
        .join(' && ') || 'true'
 
      validate('var %s = Object.keys(%s)', keys, name)
        ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i)
          ('if (%s) {', additionalProp)
 
      if (node.additionalProperties === false) {
        if (filter) validate('delete %s', name+'['+keys+'['+i+']]')
        error('has additional properties', null, JSON.stringify(name+'.') + ' + ' + keys + '['+i+']')
      } else {
        visit(name+'['+keys+'['+i+']]', node.additionalProperties, reporter, filter)
      }
 
      validate
          ('}')
        ('}')
 
      if (type !== 'object') validate('}')
    }
 
    if (node.$ref) {
      var sub = get(root, opts && opts.schemas || {}, node.$ref)
      if (sub) {
        var fn = cache[node.$ref]
        if (!fn) {
          cache[node.$ref] = function proxy(data) {
            return fn(data)
          }
          fn = compile(sub, cache, root, false, opts)
        }
        var n = gensym('ref')
        scope[n] = fn
        validate('if (!(%s(%s))) {', n, name)
        error('referenced schema does not match')
        validate('}')
      }
    }
 
    if (node.not) {
      var prev = gensym('prev')
      validate('var %s = errors', prev)
      visit(name, node.not, false, filter)
      validate('if (%s === errors) {', prev)
      error('negative schema matches')
      validate('} else {')
        ('errors = %s', prev)
      ('}')
    }
 
    if (node.items && !tuple) {
      if (type !== 'array') validate('if (%s) {', types.array(name))
 
      var i = genloop()
      validate('for (var %s = 0; %s < %s.length; %s++) {', i, i, name, i)
      visit(name+'['+i+']', node.items, reporter, filter)
      validate('}')
 
      if (type !== 'array') validate('}')
    }
 
    if (node.patternProperties) {
      if (type !== 'object') validate('if (%s) {', types.object(name))
      var keys = gensym('keys')
      var i = genloop()
      validate
        ('var %s = Object.keys(%s)', keys, name)
        ('for (var %s = 0; %s < %s.length; %s++) {', i, i, keys, i)
 
      Object.keys(node.patternProperties).forEach(function(key) {
        var p = patterns(key)
        validate('if (%s.test(%s)) {', p, keys+'['+i+']')
        visit(name+'['+keys+'['+i+']]', node.patternProperties[key], reporter, filter)
        validate('}')
      })
 
      validate('}')
      if (type !== 'object') validate('}')
    }
 
    if (node.pattern) {
      var p = patterns(node.pattern)
      if (type !== 'string') validate('if (%s) {', types.string(name))
      validate('if (!(%s.test(%s))) {', p, name)
      error('pattern mismatch')
      validate('}')
      if (type !== 'string') validate('}')
    }
 
    if (node.allOf) {
      node.allOf.forEach(function(sch) {
        visit(name, sch, reporter, filter)
      })
    }
 
    if (node.anyOf && node.anyOf.length) {
      var prev = gensym('prev')
 
      node.anyOf.forEach(function(sch, i) {
        if (i === 0) {
          validate('var %s = errors', prev)
        } else {          
          validate('if (errors !== %s) {', prev)
            ('errors = %s', prev)
        }
        visit(name, sch, false, false)
      })
      node.anyOf.forEach(function(sch, i) {
        if (i) validate('}')
      })
      validate('if (%s !== errors) {', prev)
      error('no schemas match')
      validate('}')
    }
 
    if (node.oneOf && node.oneOf.length) {
      var prev = gensym('prev')
      var passes = gensym('passes')
 
      validate
        ('var %s = errors', prev)
        ('var %s = 0', passes)
 
      node.oneOf.forEach(function(sch, i) {
        visit(name, sch, false, false)
        validate('if (%s === errors) {', prev)
          ('%s++', passes)
        ('} else {')
          ('errors = %s', prev)
        ('}')
      })
 
      validate('if (%s !== 1) {', passes)
      error('no (or more than one) schemas match')
      validate('}')
    }
 
    if (node.multipleOf !== undefined) {
      if (type !== 'number' && type !== 'integer') validate('if (%s) {', types.number(name))
 
      var factor = ((node.multipleOf | 0) !== node.multipleOf) ? Math.pow(10, node.multipleOf.toString().split('.').pop().length) : 1
      if (factor > 1) validate('if ((%d*%s) % %d) {', factor, name, factor*node.multipleOf)
      else validate('if (%s % %d) {', name, node.multipleOf)
 
      error('has a remainder')
      validate('}')
 
      if (type !== 'number' && type !== 'integer') validate('}')
    }
 
    if (node.maxProperties !== undefined) {
      if (type !== 'object') validate('if (%s) {', types.object(name))
      
      validate('if (Object.keys(%s).length > %d) {', name, node.maxProperties)
      error('has more properties than allowed')
      validate('}')
 
      if (type !== 'object') validate('}')
    }
 
    if (node.minProperties !== undefined) {
      if (type !== 'object') validate('if (%s) {', types.object(name))
      
      validate('if (Object.keys(%s).length < %d) {', name, node.minProperties)
      error('has less properties than allowed')
      validate('}')
 
      if (type !== 'object') validate('}')
    }
 
    if (node.maxItems !== undefined) {
      if (type !== 'array') validate('if (%s) {', types.array(name))
      
      validate('if (%s.length > %d) {', name, node.maxItems)
      error('has more items than allowed')
      validate('}')
 
      if (type !== 'array') validate('}')
    }
 
    if (node.minItems !== undefined) {
      if (type !== 'array') validate('if (%s) {', types.array(name))
      
      validate('if (%s.length < %d) {', name, node.minItems)
      error('has less items than allowed')
      validate('}')
 
      if (type !== 'array') validate('}')
    }
 
    if (node.maxLength !== undefined) {
      if (type !== 'string') validate('if (%s) {', types.string(name))
 
      validate('if (%s.length > %d) {', name, node.maxLength)
      error('has longer length than allowed')
      validate('}')
 
      if (type !== 'string') validate('}')
    }
 
    if (node.minLength !== undefined) {
      if (type !== 'string') validate('if (%s) {', types.string(name))
 
      validate('if (%s.length < %d) {', name, node.minLength)
      error('has less length than allowed')
      validate('}')
 
      if (type !== 'string') validate('}')
    }
 
    if (node.minimum !== undefined) {
      validate('if (%s %s %d) {', name, node.exclusiveMinimum ? '<=' : '<', node.minimum)
      error('is less than minimum')
      validate('}')
    }
 
    if (node.maximum !== undefined) {
      validate('if (%s %s %d) {', name, node.exclusiveMaximum ? '>=' : '>', node.maximum)
      error('is more than maximum')
      validate('}')
    }
 
    if (properties) {
      Object.keys(properties).forEach(function(p) {
        visit(genobj(name, p), properties[p], reporter, filter)
      })
    }
 
    while (indent--) validate('}')
  }
 
  var validate = genfun
    ('function validate(data) {')
      ('validate.errors = null')
      ('var errors = 0')
 
  visit('data', schema, reporter, opts && opts.filter)
 
  validate
      ('return errors === 0')
    ('}')
 
  validate = validate.toFunction(scope)
  validate.errors = null
 
  validate.__defineGetter__('error', function() {
    if (!validate.errors) return ''
    return validate.errors
      .map(function(err) {
        return err.field+' '+err.message
      })
      .join('\n')
  })
 
  validate.toJSON = function() {
    return schema
  }
 
  return validate
}
 
module.exports = function(schema, opts) {
  if (typeof schema === 'string') schema = JSON.parse(schema)
  return compile(schema, {}, schema, true, opts)
}
 
module.exports.filter = function(schema, opts) {
  var validate = module.exports(schema, xtend(opts, {filter: true}))
  return function(sch) {
    validate(sch)
    return sch
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/

Statements: 9.76% (4 / 41)      Branches: 0% (0 / 14)      Functions: 0% (0 / 7)      Lines: 10.53% (4 / 38)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/
File Statements Branches Functions Lines
index.js 9.76% (4 / 41) 0% (0 / 14) 0% (0 / 7) 10.53% (4 / 38)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-function/index.js

Statements: 9.76% (4 / 41)      Branches: 0% (0 / 14)      Functions: 0% (0 / 7)      Lines: 10.53% (4 / 38)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631   1 1   1                                                                                                                  
var util = require('util')
 
var INDENT_START = /[\{\[]/
var INDENT_END = /[\}\]]/
 
module.exports = function() {
  var lines = []
  var indent = 0
 
  var push = function(str) {
    var spaces = ''
    while (spaces.length < indent*2) spaces += '  '
    lines.push(spaces+str)
  }
 
  var line = function(fmt) {
    if (!fmt) return line
 
    if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) {
      indent--
      push(util.format.apply(util, arguments))
      indent++
      return line
    }
    if (INDENT_START.test(fmt[fmt.length-1])) {
      push(util.format.apply(util, arguments))
      indent++
      return line
    }
    if (INDENT_END.test(fmt.trim()[0])) {
      indent--
      push(util.format.apply(util, arguments))
      return line
    }
 
    push(util.format.apply(util, arguments))
    return line
  }
 
  line.toString = function() {
    return lines.join('\n')
  }
 
  line.toFunction = function(scope) {
    var src = 'return ('+line.toString()+')'
 
    var keys = Object.keys(scope || {}).map(function(key) {
      return key
    })
 
    var vals = keys.map(function(key) {
      return scope[key]
    })
 
    return Function.apply(null, keys.concat(src)).apply(null, vals)
  }
 
  if (arguments.length) line.apply(null, arguments)
 
  return line
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/

Statements: 71.43% (5 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 71.43% (5 / 7)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/
File Statements Branches Functions Lines
index.js 71.43% (5 / 7) 0% (0 / 4) 0% (0 / 2) 71.43% (5 / 7)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/index.js

Statements: 71.43% (5 / 7)      Branches: 0% (0 / 4)      Functions: 0% (0 / 2)      Lines: 71.43% (5 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 141   1       1 1       1    
var isProperty = require('is-property')
 
var gen = function(obj, prop) {
  return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']'
}
 
gen.valid = isProperty
gen.property = function (prop) {
 return isProperty(prop) ? prop : JSON.stringify(prop)
}
 
module.exports = gen
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/

Statements: 66.67% (2 / 3)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/
File Statements Branches Functions Lines
is-property.js 66.67% (2 / 3) 100% (0 / 0) 0% (0 / 1) 66.67% (2 / 3)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/is-property.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/generate-object-property/node_modules/is-property/is-property.js

Statements: 66.67% (2 / 3)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 66.67% (2 / 3)      Ignored: none     

1 2 3 4 5 6  1     1  
"use strict"
function isProperty(str) {
  return /^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(str)
}
module.exports = isProperty
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/

Statements: 17.78% (8 / 45)      Branches: 0% (0 / 22)      Functions: 0% (0 / 6)      Lines: 17.78% (8 / 45)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/
File Statements Branches Functions Lines
jsonpointer.js 17.78% (8 / 45) 0% (0 / 22) 0% (0 / 6) 17.78% (8 / 45)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer/jsonpointer.js

Statements: 17.78% (8 / 45)      Branches: 0% (0 / 22)      Functions: 0% (0 / 6)      Lines: 17.78% (8 / 45)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 811   1                       1                                                 1                                           1               1               1 1    
var console = require("console");
 
var untilde = function(str) {
  return str.replace(/~./g, function(m) {
    switch (m) {
      case "~0":
        return "~";
      case "~1":
        return "/";
    }
    throw("Invalid tilde escape: " + m);
  });
}
 
var traverse = function(obj, pointer, value) {
  // assert(isArray(pointer))
  var part = untilde(pointer.shift());
  if(typeof obj[part] === "undefined") {
    throw("Value for pointer '" + pointer + "' not found.");
    return;
  }
  if(pointer.length !== 0) { // keep traversin!
    return traverse(obj[part], pointer, value);
  }
  // we're done
  if(typeof value === "undefined") {
    // just reading
    return obj[part];
  }
  // set new value, return old value
  var old_value = obj[part];
  if(value === null) {
    delete obj[part];
  } else {
    obj[part] = value;
  }
  return old_value;
}
 
var validate_input = function(obj, pointer) {
  if(typeof obj !== "object") {
    throw("Invalid input object.");
  }
 
  if(pointer === "") {
    return [];
  }
 
  if(!pointer) {
    throw("Invalid JSON pointer.");
  }
 
  pointer = pointer.split("/");
  var first = pointer.shift();
  if (first !== "") {
    throw("Invalid JSON pointer.");
  }
 
  return pointer;
}
 
var get = function(obj, pointer) {
  pointer = validate_input(obj, pointer);
  if (pointer.length === 0) {
    return obj;
  }
  return traverse(obj, pointer);
}
 
var set = function(obj, pointer, value) {
  pointer = validate_input(obj, pointer);
  if (pointer.length === 0) {
    throw("Invalid JSON pointer for set.")
  }
  return traverse(obj, pointer, value);
}
 
exports.get = get
exports.set = set
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/

Statements: 22.22% (2 / 9)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 22.22% (2 / 9)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/
File Statements Branches Functions Lines
immutable.js 22.22% (2 / 9) 0% (0 / 2) 0% (0 / 1) 22.22% (2 / 9)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/immutable.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/xtend/immutable.js

Statements: 22.22% (2 / 9)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 22.22% (2 / 9)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 191   1                                
module.exports = extend
 
function extend() {
    var target = {}
 
    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i]
 
        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key]
            }
        }
    }
 
    return target
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/

Statements: 45.45% (10 / 22)      Branches: 0% (0 / 6)      Functions: 20% (1 / 5)      Lines: 45.45% (10 / 22)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/
File Statements Branches Functions Lines
error.js 60% (3 / 5) 100% (0 / 0) 0% (0 / 1) 60% (3 / 5)
index.js 41.18% (7 / 17) 0% (0 / 6) 25% (1 / 4) 41.18% (7 / 17)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/error.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/error.js

Statements: 60% (3 / 5)      Branches: 100% (0 / 0)      Functions: 0% (0 / 1)      Lines: 60% (3 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12    1         1   1    
'use strict'
 
function ValidationError (errors) {
  this.name = 'ValidationError'
  this.errors = errors
}
 
ValidationError.prototype = Error.prototype
 
module.exports = ValidationError
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/index.js

Statements: 41.18% (7 / 17)      Branches: 0% (0 / 6)      Functions: 25% (1 / 4)      Lines: 41.18% (7 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41    1 1 1   1                                               1       1 15          
'use strict'
 
var schemas = require('./schemas')
var ValidationError = require('./error')
var validator = require('is-my-json-valid')
 
var runner = function (schema, data, cb) {
  var validate = validator(schema, {
    greedy: true,
    verbose: true,
    schemas: schemas
  })
 
  var valid = false
 
  if (data !== undefined) {
    // execute is-my-json-valid
    valid = validate(data)
  }
 
  // callback?
  if (!cb) {
    return !validate.errors > 0
  } else {
    return cb(validate.errors ? new ValidationError(validate.errors) : null, valid)
  }
 
  return valid
}
 
module.exports = function (data, cb) {
  return runner(schemas.har, data, cb)
}
 
Object.keys(schemas).map(function (name) {
  module.exports[name] = function (data, cb) {
    return runner(schemas[name], data, cb)
  }
})
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/schemas/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/schemas/

Statements: 100% (21 / 21)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (21 / 21)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/schemas/
File Statements Branches Functions Lines
index.js 100% (21 / 21) 100% (0 / 0) 100% (0 / 0) 100% (21 / 21)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/schemas/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/har-validator/src/schemas/index.js

Statements: 100% (21 / 21)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (21 / 21)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51    1                                       1 1   1   1 1 1 1   1 1 1   1 1 1 1   1 1 1 1   1   1    
'use strict'
 
var schemas = {
  cache: require('./cache.json'),
  cacheEntry: require('./cacheEntry.json'),
  content: require('./content.json'),
  cookie: require('./cookie.json'),
  creator: require('./creator.json'),
  entry: require('./entry.json'),
  har: require('./har.json'),
  log: require('./log.json'),
  page: require('./page.json'),
  pageTimings: require('./pageTimings.json'),
  postData: require('./postData.json'),
  record: require('./record.json'),
  request: require('./request.json'),
  response: require('./response.json'),
  timings: require('./timings.json')
}
 
// is-my-json-valid does not provide meaningful error messages for external schemas
// this is a workaround
schemas.cache.properties.beforeRequest = schemas.cacheEntry
schemas.cache.properties.afterRequest = schemas.cacheEntry
 
schemas.page.properties.pageTimings = schemas.pageTimings
 
schemas.request.properties.cookies.items = schemas.cookie
schemas.request.properties.headers.items = schemas.record
schemas.request.properties.queryString.items = schemas.record
schemas.request.properties.postData = schemas.postData
 
schemas.response.properties.cookies.items = schemas.cookie
schemas.response.properties.headers.items = schemas.record
schemas.response.properties.content = schemas.content
 
schemas.entry.properties.request = schemas.request
schemas.entry.properties.response = schemas.response
schemas.entry.properties.cache = schemas.cache
schemas.entry.properties.timings = schemas.timings
 
schemas.log.properties.creator = schemas.creator
schemas.log.properties.browser = schemas.creator
schemas.log.properties.pages.items = schemas.page
schemas.log.properties.entries.items = schemas.entry
 
schemas.har.properties.log = schemas.log
 
module.exports = schemas
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
module.exports = require('./lib');
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/

Statements: 15.74% (54 / 343)      Branches: 0% (0 / 326)      Functions: 0% (0 / 33)      Lines: 15.84% (54 / 341)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/
File Statements Branches Functions Lines
client.js 11.49% (10 / 87) 0% (0 / 120) 0% (0 / 4) 11.49% (10 / 87)
crypto.js 30.23% (13 / 43) 0% (0 / 18) 0% (0 / 7) 30.23% (13 / 43)
index.js 100% (7 / 7) 100% (0 / 0) 100% (0 / 0) 100% (7 / 7)
server.js 8.45% (12 / 142) 0% (0 / 138) 0% (0 / 13) 8.57% (12 / 140)
utils.js 18.75% (12 / 64) 0% (0 / 50) 0% (0 / 9) 18.75% (12 / 64)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/client.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/client.js

Statements: 11.49% (10 / 87)      Branches: 0% (0 / 120)      Functions: 0% (0 / 4)      Lines: 11.49% (10 / 87)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371    1 1 1 1 1         1                                                               1                                                                                                                                                                                                             1                                                                                                                                                                   1                                                                                                                                                                       1                                                                                                                    
// Load modules
 
var Url = require('url');
var Hoek = require('hoek');
var Cryptiles = require('cryptiles');
var Crypto = require('./crypto');
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {};
 
 
// Generate an Authorization header for a given request
 
/*
    uri: 'http://example.com/resource?a=b' or object from Url.parse()
    method: HTTP verb (e.g. 'GET', 'POST')
    options: {
 
        // Required
 
        credentials: {
            id: 'dh37fgj492je',
            key: 'aoijedoaijsdlaksjdl',
            algorithm: 'sha256'                                 // 'sha1', 'sha256'
        },
 
        // Optional
 
        ext: 'application-specific',                        // Application specific data sent via the ext attribute
        timestamp: Date.now(),                              // A pre-calculated timestamp
        nonce: '2334f34f',                                  // A pre-generated nonce
        localtimeOffsetMsec: 400,                           // Time offset to sync with server time (ignored if timestamp provided)
        payload: '{"some":"payload"}',                      // UTF-8 encoded string for body hash generation (ignored if hash provided)
        contentType: 'application/json',                    // Payload content-type (ignored if hash provided)
        hash: 'U4MKKSmiVxk37JCCrAVIjV=',                    // Pre-calculated payload hash
        app: '24s23423f34dx',                               // Oz application id
        dlg: '234sz34tww3sd'                                // Oz delegated-by application id
    }
*/
 
exports.header = function (uri, method, options) {
 
    var result = {
        field: '',
        artifacts: {}
    };
 
    // Validate inputs
 
    if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
        !method || typeof method !== 'string' ||
        !options || typeof options !== 'object') {
 
        result.err = 'Invalid argument type';
        return result;
    }
 
    // Application time
 
    var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
 
    // Validate credentials
 
    var credentials = options.credentials;
    if (!credentials ||
        !credentials.id ||
        !credentials.key ||
        !credentials.algorithm) {
 
        result.err = 'Invalid credential object';
        return result;
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        result.err = 'Unknown algorithm';
        return result;
    }
 
    // Parse URI
 
    if (typeof uri === 'string') {
        uri = Url.parse(uri);
    }
 
    // Calculate signature
 
    var artifacts = {
        ts: timestamp,
        nonce: options.nonce || Cryptiles.randomString(6),
        method: method,
        resource: uri.pathname + (uri.search || ''),                            // Maintain trailing '?'
        host: uri.hostname,
        port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
        hash: options.hash,
        ext: options.ext,
        app: options.app,
        dlg: options.dlg
    };
 
    result.artifacts = artifacts;
 
    // Calculate payload hash
 
    if (!artifacts.hash &&
        (options.payload || options.payload === '')) {
 
        artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
    }
 
    var mac = Crypto.calculateMac('header', credentials, artifacts);
 
    // Construct header
 
    var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '';       // Other falsey values allowed
    var header = 'Hawk id="' + credentials.id +
                 '", ts="' + artifacts.ts +
                 '", nonce="' + artifacts.nonce +
                 (artifacts.hash ? '", hash="' + artifacts.hash : '') +
                 (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') +
                 '", mac="' + mac + '"';
 
    if (artifacts.app) {
        header += ', app="' + artifacts.app +
                  (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"';
    }
 
    result.field = header;
 
    return result;
};
 
 
// Validate server response
 
/*
    res:        node's response object
    artifacts:  object received from header().artifacts
    options: {
        payload:    optional payload received
        required:   specifies if a Server-Authorization header is required. Defaults to 'false'
    }
*/
 
exports.authenticate = function (res, credentials, artifacts, options) {
 
    artifacts = Hoek.clone(artifacts);
    options = options || {};
 
    if (res.headers['www-authenticate']) {
 
        // Parse HTTP WWW-Authenticate header
 
        var attributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']);
        if (attributes instanceof Error) {
            return false;
        }
 
        // Validate server timestamp (not used to update clock since it is done via the SNPT client)
 
        if (attributes.ts) {
            var tsm = Crypto.calculateTsMac(attributes.ts, credentials);
            if (tsm !== attributes.tsm) {
                return false;
            }
        }
    }
 
    // Parse HTTP Server-Authorization header
 
    if (!res.headers['server-authorization'] &&
        !options.required) {
 
        return true;
    }
 
    var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']);
    if (attributes instanceof Error) {
        return false;
    }
 
    artifacts.ext = attributes.ext;
    artifacts.hash = attributes.hash;
 
    var mac = Crypto.calculateMac('response', credentials, artifacts);
    if (mac !== attributes.mac) {
        return false;
    }
 
    if (!options.payload &&
        options.payload !== '') {
 
        return true;
    }
 
    if (!attributes.hash) {
        return false;
    }
 
    var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']);
    return (calculatedHash === attributes.hash);
};
 
 
// Generate a bewit value for a given URI
 
/*
    uri: 'http://example.com/resource?a=b' or object from Url.parse()
    options: {
 
        // Required
 
        credentials: {
            id: 'dh37fgj492je',
            key: 'aoijedoaijsdlaksjdl',
            algorithm: 'sha256'                             // 'sha1', 'sha256'
        },
        ttlSec: 60 * 60,                                    // TTL in seconds
 
        // Optional
 
        ext: 'application-specific',                        // Application specific data sent via the ext attribute
        localtimeOffsetMsec: 400                            // Time offset to sync with server time
    };
*/
 
exports.getBewit = function (uri, options) {
 
    // Validate inputs
 
    if (!uri ||
        (typeof uri !== 'string' && typeof uri !== 'object') ||
        !options ||
        typeof options !== 'object' ||
        !options.ttlSec) {
 
        return '';
    }
 
    options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext);       // Zero is valid value
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);
 
    // Validate credentials
 
    var credentials = options.credentials;
    if (!credentials ||
        !credentials.id ||
        !credentials.key ||
        !credentials.algorithm) {
 
        return '';
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        return '';
    }
 
    // Parse URI
 
    if (typeof uri === 'string') {
        uri = Url.parse(uri);
    }
 
    // Calculate signature
 
    var exp = Math.floor(now / 1000) + options.ttlSec;
    var mac = Crypto.calculateMac('bewit', credentials, {
        ts: exp,
        nonce: '',
        method: 'GET',
        resource: uri.pathname + (uri.search || ''),                            // Maintain trailing '?'
        host: uri.hostname,
        port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
        ext: options.ext
    });
 
    // Construct bewit: id\exp\mac\ext
 
    var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
    return Hoek.base64urlEncode(bewit);
};
 
 
// Generate an authorization string for a message
 
/*
    host: 'example.com',
    port: 8000,
    message: '{"some":"payload"}',                          // UTF-8 encoded string for body hash generation
    options: {
 
        // Required
 
        credentials: {
            id: 'dh37fgj492je',
            key: 'aoijedoaijsdlaksjdl',
            algorithm: 'sha256'                             // 'sha1', 'sha256'
        },
 
        // Optional
 
        timestamp: Date.now(),                              // A pre-calculated timestamp
        nonce: '2334f34f',                                  // A pre-generated nonce
        localtimeOffsetMsec: 400,                           // Time offset to sync with server time (ignored if timestamp provided)
    }
*/
 
exports.message = function (host, port, message, options) {
 
    // Validate inputs
 
    if (!host || typeof host !== 'string' ||
        !port || typeof port !== 'number' ||
        message === null || message === undefined || typeof message !== 'string' ||
        !options || typeof options !== 'object') {
 
        return null;
    }
 
    // Application time
 
    var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
 
    // Validate credentials
 
    var credentials = options.credentials;
    if (!credentials ||
        !credentials.id ||
        !credentials.key ||
        !credentials.algorithm) {
 
        // Invalid credential object
        return null;
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        return null;
    }
 
    // Calculate signature
 
    var artifacts = {
        ts: timestamp,
        nonce: options.nonce || Cryptiles.randomString(6),
        host: host,
        port: port,
        hash: Crypto.calculatePayloadHash(message, credentials.algorithm)
    };
 
    // Construct authorization
 
    var result = {
        id: credentials.id,
        ts: artifacts.ts,
        nonce: artifacts.nonce,
        hash: artifacts.hash,
        mac: Crypto.calculateMac('message', credentials, artifacts)
    };
 
    return result;
};
 
 
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/crypto.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/crypto.js

Statements: 30.23% (13 / 43)      Branches: 0% (0 / 18)      Functions: 0% (0 / 7)      Lines: 30.23% (13 / 43)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128    1 1 1         1         1         1                                                 1                   1                                                                   1               1                 1             1               1              
// Load modules
 
var Crypto = require('crypto');
var Url = require('url');
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {};
 
 
// MAC normalization format version
 
exports.headerVersion = '1';                        // Prevent comparison of mac values generated with different normalized string formats
 
 
// Supported HMAC algorithms
 
exports.algorithms = ['sha1', 'sha256'];
 
 
// Calculate the request MAC
 
/*
    type: 'header',                                 // 'header', 'bewit', 'response'
    credentials: {
        key: 'aoijedoaijsdlaksjdl',
        algorithm: 'sha256'                         // 'sha1', 'sha256'
    },
    options: {
        method: 'GET',
        resource: '/resource?a=1&b=2',
        host: 'example.com',
        port: 8080,
        ts: 1357718381034,
        nonce: 'd3d345f',
        hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=',
        ext: 'app-specific-data',
        app: 'hf48hd83qwkj',                        // Application id (Oz)
        dlg: 'd8djwekds9cj'                         // Delegated by application id (Oz), requires options.app
    }
*/
 
exports.calculateMac = function (type, credentials, options) {
 
    var normalized = exports.generateNormalizedString(type, options);
 
    var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized);
    var digest = hmac.digest('base64');
    return digest;
};
 
 
exports.generateNormalizedString = function (type, options) {
 
    var resource = options.resource || '';
    if (resource &&
        resource[0] !== '/') {
 
        var url = Url.parse(resource, false);
        resource = url.path;                        // Includes query
    }
 
    var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' +
                     options.ts + '\n' +
                     options.nonce + '\n' +
                     (options.method || '').toUpperCase() + '\n' +
                     resource + '\n' +
                     options.host.toLowerCase() + '\n' +
                     options.port + '\n' +
                     (options.hash || '') + '\n';
 
    if (options.ext) {
        normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n');
    }
 
    normalized += '\n';
 
    if (options.app) {
        normalized += options.app + '\n' +
                      (options.dlg || '') + '\n';
    }
 
    return normalized;
};
 
 
exports.calculatePayloadHash = function (payload, algorithm, contentType) {
 
    var hash = exports.initializePayloadHash(algorithm, contentType);
    hash.update(payload || '');
    return exports.finalizePayloadHash(hash);
};
 
 
exports.initializePayloadHash = function (algorithm, contentType) {
 
    var hash = Crypto.createHash(algorithm);
    hash.update('hawk.' + exports.headerVersion + '.payload\n');
    hash.update(Utils.parseContentType(contentType) + '\n');
    return hash;
};
 
 
exports.finalizePayloadHash = function (hash) {
 
    hash.update('\n');
    return hash.digest('base64');
};
 
 
exports.calculateTsMac = function (ts, credentials) {
 
    var hmac = Crypto.createHmac(credentials.algorithm, credentials.key);
    hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n');
    return hmac.digest('base64');
};
 
 
exports.timestampMessage = function (credentials, localtimeOffsetMsec) {
 
    var now = Utils.nowSecs(localtimeOffsetMsec);
    var tsm = exports.calculateTsMac(now, credentials);
    return { ts: now, tsm: tsm };
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/index.js

Statements: 100% (7 / 7)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (7 / 7)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17    1 1   1 1 1 1   1            
// Export sub-modules
 
exports.error = exports.Error = require('boom');
exports.sntp = require('sntp');
 
exports.server = require('./server');
exports.client = require('./client');
exports.crypto = require('./crypto');
exports.utils = require('./utils');
 
exports.uri = {
    authenticate: exports.server.authenticateBewit,
    getBewit: exports.client.getBewit
};
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/server.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/server.js

Statements: 8.45% (12 / 142)      Branches: 0% (0 / 138)      Functions: 0% (0 / 13)      Lines: 8.57% (12 / 140)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536    1 1 1 1 1         1                                                                                                                                                 1                                                                                                                                                                                                                                                                   1                           1                                     1                                                                                                                             1                                                                                                                                                                                                                                                                           1                                                                                                                                                                                      
// Load modules
 
var Boom = require('boom');
var Hoek = require('hoek');
var Cryptiles = require('cryptiles');
var Crypto = require('./crypto');
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {};
 
 
// Hawk authentication
 
/*
   req:                 node's HTTP request object or an object as follows:
  
                        var request = {
                            method: 'GET',
                            url: '/resource/4?a=1&b=2',
                            host: 'example.com',
                            port: 8080,
                            authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="'
                        };
  
   credentialsFunc:     required function to lookup the set of Hawk credentials based on the provided credentials id.
                        The credentials include the MAC key, MAC algorithm, and other attributes (such as username)
                        needed by the application. This function is the equivalent of verifying the username and
                        password in Basic authentication.
  
                        var credentialsFunc = function (id, callback) {
    
                            // Lookup credentials in database
                            db.lookup(id, function (err, item) {
    
                                if (err || !item) {
                                    return callback(err);
                                }
    
                                var credentials = {
                                    // Required
                                    key: item.key,
                                    algorithm: item.algorithm,
                                    // Application specific
                                    user: item.user
                                };
    
                                return callback(null, credentials);
                            });
                        };
  
   options: {
 
        hostHeaderName:        optional header field name, used to override the default 'Host' header when used
                               behind a cache of a proxy. Apache2 changes the value of the 'Host' header while preserving
                               the original (which is what the module must verify) in the 'x-forwarded-host' header field.
                               Only used when passed a node Http.ServerRequest object.
  
        nonceFunc:             optional nonce validation function. The function signature is function(nonce, ts, callback)
                               where 'callback' must be called using the signature function(err).
  
        timestampSkewSec:      optional number of seconds of permitted clock skew for incoming timestamps. Defaults to 60 seconds.
                               Provides a +/- skew which means actual allowed window is double the number of seconds.
  
        localtimeOffsetMsec:   optional local clock time offset express in a number of milliseconds (positive or negative).
                               Defaults to 0.
  
        payload:               optional payload for validation. The client calculates the hash value and includes it via the 'hash'
                               header attribute. The server always ensures the value provided has been included in the request
                               MAC. When this option is provided, it validates the hash value itself. Validation is done by calculating
                               a hash value over the entire payload (assuming it has already be normalized to the same format and
                               encoding used by the client to calculate the hash on request). If the payload is not available at the time
                               of authentication, the authenticatePayload() method can be used by passing it the credentials and
                               attributes.hash returned in the authenticate callback.
 
        host:                  optional host name override. Only used when passed a node request object.
        port:                  optional port override. Only used when passed a node request object.
    }
 
    callback: function (err, credentials, artifacts) { }
 */
 
exports.authenticate = function (req, credentialsFunc, options, callback) {
 
    callback = Hoek.nextTick(callback);
    
    // Default options
 
    options.nonceFunc = options.nonceFunc || function (nonce, ts, nonceCallback) { return nonceCallback(); };   // No validation
    options.timestampSkewSec = options.timestampSkewSec || 60;                                                  // 60 seconds
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);                           // Measure now before any other processing
 
    // Convert node Http request object to a request configuration object
 
    var request = Utils.parseRequest(req, options);
    if (request instanceof Error) {
        return callback(Boom.badRequest(request.message));
    }
 
    // Parse HTTP Authorization header
 
    var attributes = Utils.parseAuthorizationHeader(request.authorization);
    if (attributes instanceof Error) {
        return callback(attributes);
    }
 
    // Construct artifacts container
 
    var artifacts = {
        method: request.method,
        host: request.host,
        port: request.port,
        resource: request.url,
        ts: attributes.ts,
        nonce: attributes.nonce,
        hash: attributes.hash,
        ext: attributes.ext,
        app: attributes.app,
        dlg: attributes.dlg,
        mac: attributes.mac,
        id: attributes.id
    };
 
    // Verify required header attributes
 
    if (!attributes.id ||
        !attributes.ts ||
        !attributes.nonce ||
        !attributes.mac) {
 
        return callback(Boom.badRequest('Missing attributes'), null, artifacts);
    }
 
    // Fetch Hawk credentials
 
    credentialsFunc(attributes.id, function (err, credentials) {
 
        if (err) {
            return callback(err, credentials || null, artifacts);
        }
 
        if (!credentials) {
            return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, artifacts);
        }
 
        if (!credentials.key ||
            !credentials.algorithm) {
 
            return callback(Boom.internal('Invalid credentials'), credentials, artifacts);
        }
 
        if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
            return callback(Boom.internal('Unknown algorithm'), credentials, artifacts);
        }
 
        // Calculate MAC
 
        var mac = Crypto.calculateMac('header', credentials, artifacts);
        if (!Cryptiles.fixedTimeComparison(mac, attributes.mac)) {
            return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, artifacts);
        }
 
        // Check payload hash
 
        if (options.payload ||
            options.payload === '') {
 
            if (!attributes.hash) {
                return callback(Boom.unauthorized('Missing required payload hash', 'Hawk'), credentials, artifacts);
            }
 
            var hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.contentType);
            if (!Cryptiles.fixedTimeComparison(hash, attributes.hash)) {
                return callback(Boom.unauthorized('Bad payload hash', 'Hawk'), credentials, artifacts);
            }
        }
 
        // Check nonce
 
        options.nonceFunc(attributes.nonce, attributes.ts, function (err) {
 
            if (err) {
                return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials, artifacts);
            }
 
            // Check timestamp staleness
 
            if (Math.abs((attributes.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
                var tsm = Crypto.timestampMessage(credentials, options.localtimeOffsetMsec);
                return callback(Boom.unauthorized('Stale timestamp', 'Hawk', tsm), credentials, artifacts);
            }
 
            // Successful authentication
 
            return callback(null, credentials, artifacts);
        });
    });
};
 
 
// Authenticate payload hash - used when payload cannot be provided during authenticate()
 
/*
    payload:        raw request payload
    credentials:    from authenticate callback
    artifacts:      from authenticate callback
    contentType:    req.headers['content-type']
*/
 
exports.authenticatePayload = function (payload, credentials, artifacts, contentType) {
 
    var calculatedHash = Crypto.calculatePayloadHash(payload, credentials.algorithm, contentType);
    return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
};
 
 
// Authenticate payload hash - used when payload cannot be provided during authenticate()
 
/*
    calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash()
    artifacts:      from authenticate callback
*/
 
exports.authenticatePayloadHash = function (calculatedHash, artifacts) {
 
    return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
};
 
 
// Generate a Server-Authorization header for a given response
 
/*
    credentials: {},                                        // Object received from authenticate()
    artifacts: {}                                           // Object received from authenticate(); 'mac', 'hash', and 'ext' - ignored
    options: {
        ext: 'application-specific',                        // Application specific data sent via the ext attribute
        payload: '{"some":"payload"}',                      // UTF-8 encoded string for body hash generation (ignored if hash provided)
        contentType: 'application/json',                    // Payload content-type (ignored if hash provided)
        hash: 'U4MKKSmiVxk37JCCrAVIjV='                     // Pre-calculated payload hash
    }
*/
 
exports.header = function (credentials, artifacts, options) {
 
    // Prepare inputs
 
    options = options || {};
 
    if (!artifacts ||
        typeof artifacts !== 'object' ||
        typeof options !== 'object') {
 
        return '';
    }
 
    artifacts = Hoek.clone(artifacts);
    delete artifacts.mac;
    artifacts.hash = options.hash;
    artifacts.ext = options.ext;
 
    // Validate credentials
 
    if (!credentials ||
        !credentials.key ||
        !credentials.algorithm) {
 
        // Invalid credential object
        return '';
    }
 
    if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
        return '';
    }
 
    // Calculate payload hash
 
    if (!artifacts.hash &&
        (options.payload || options.payload === '')) {
 
        artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
    }
 
    var mac = Crypto.calculateMac('response', credentials, artifacts);
 
    // Construct header
 
    var header = 'Hawk mac="' + mac + '"' +
                 (artifacts.hash ? ', hash="' + artifacts.hash + '"' : '');
 
    if (artifacts.ext !== null &&
        artifacts.ext !== undefined &&
        artifacts.ext !== '') {                       // Other falsey values allowed
 
        header += ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"';
    }
 
    return header;
};
 
 
/*
 * Arguments and options are the same as authenticate() with the exception that the only supported options are:
 * 'hostHeaderName', 'localtimeOffsetMsec', 'host', 'port'
 */
 
exports.authenticateBewit = function (req, credentialsFunc, options, callback) {
 
    callback = Hoek.nextTick(callback);
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);
 
    // Convert node Http request object to a request configuration object
 
    var request = Utils.parseRequest(req, options);
    if (request instanceof Error) {
        return callback(Boom.badRequest(request.message));
    }
 
    // Extract bewit
 
    //                                 1     2             3           4     
    var resource = request.url.match(/^(\/.*)([\?&])bewit\=([^&$]*)(?:&(.+))?$/);
    if (!resource) {
        return callback(Boom.unauthorized(null, 'Hawk'));
    }
 
    // Bewit not empty
 
    if (!resource[3]) {
        return callback(Boom.unauthorized('Empty bewit', 'Hawk'));
    }
 
    // Verify method is GET
 
    if (request.method !== 'GET' &&
        request.method !== 'HEAD') {
 
        return callback(Boom.unauthorized('Invalid method', 'Hawk'));
    }
 
    // No other authentication
 
    if (request.authorization) {
        return callback(Boom.badRequest('Multiple authentications'));
    }
 
    // Parse bewit
 
    var bewitString = Hoek.base64urlDecode(resource[3]);
    if (bewitString instanceof Error) {
        return callback(Boom.badRequest('Invalid bewit encoding'));
    }
 
    // Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character)
 
    var bewitParts = bewitString.split('\\');
    if (bewitParts.length !== 4) {
        return callback(Boom.badRequest('Invalid bewit structure'));
    }
 
    var bewit = {
        id: bewitParts[0],
        exp: parseInt(bewitParts[1], 10),
        mac: bewitParts[2],
        ext: bewitParts[3] || ''
    };
 
    if (!bewit.id ||
        !bewit.exp ||
        !bewit.mac) {
 
        return callback(Boom.badRequest('Missing bewit attributes'));
    }
 
    // Construct URL without bewit
 
    var url = resource[1];
    if (resource[4]) {
        url += resource[2] + resource[4];
    }
 
    // Check expiration
 
    if (bewit.exp * 1000 <= now) {
        return callback(Boom.unauthorized('Access expired', 'Hawk'), null, bewit);
    }
 
    // Fetch Hawk credentials
 
    credentialsFunc(bewit.id, function (err, credentials) {
 
        if (err) {
            return callback(err, credentials || null, bewit.ext);
        }
 
        if (!credentials) {
            return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, bewit);
        }
 
        if (!credentials.key ||
            !credentials.algorithm) {
 
            return callback(Boom.internal('Invalid credentials'), credentials, bewit);
        }
 
        if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
            return callback(Boom.internal('Unknown algorithm'), credentials, bewit);
        }
 
        // Calculate MAC
 
        var mac = Crypto.calculateMac('bewit', credentials, {
            ts: bewit.exp,
            nonce: '',
            method: 'GET',
            resource: url,
            host: request.host,
            port: request.port,
            ext: bewit.ext
        });
 
        if (!Cryptiles.fixedTimeComparison(mac, bewit.mac)) {
            return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, bewit);
        }
 
        // Successful authentication
 
        return callback(null, credentials, bewit);
    });
};
 
 
/*
 *  options are the same as authenticate() with the exception that the only supported options are:
 * 'nonceFunc', 'timestampSkewSec', 'localtimeOffsetMsec'
 */
 
exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) {
 
    callback = Hoek.nextTick(callback);
    
    // Default options
 
    options.nonceFunc = options.nonceFunc || function (nonce, ts, nonceCallback) { return nonceCallback(); };   // No validation
    options.timestampSkewSec = options.timestampSkewSec || 60;                                                  // 60 seconds
 
    // Application time
 
    var now = Utils.now(options.localtimeOffsetMsec);                       // Measure now before any other processing
 
    // Validate authorization
    
    if (!authorization.id ||
        !authorization.ts ||
        !authorization.nonce ||
        !authorization.hash ||
        !authorization.mac) {
        
            return callback(Boom.badRequest('Invalid authorization'))
    }
 
    // Fetch Hawk credentials
 
    credentialsFunc(authorization.id, function (err, credentials) {
 
        if (err) {
            return callback(err, credentials || null);
        }
 
        if (!credentials) {
            return callback(Boom.unauthorized('Unknown credentials', 'Hawk'));
        }
 
        if (!credentials.key ||
            !credentials.algorithm) {
 
            return callback(Boom.internal('Invalid credentials'), credentials);
        }
 
        if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
            return callback(Boom.internal('Unknown algorithm'), credentials);
        }
 
        // Construct artifacts container
 
        var artifacts = {
            ts: authorization.ts,
            nonce: authorization.nonce,
            host: host,
            port: port,
            hash: authorization.hash
        };
 
        // Calculate MAC
 
        var mac = Crypto.calculateMac('message', credentials, artifacts);
        if (!Cryptiles.fixedTimeComparison(mac, authorization.mac)) {
            return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials);
        }
 
        // Check payload hash
 
        var hash = Crypto.calculatePayloadHash(message, credentials.algorithm);
        if (!Cryptiles.fixedTimeComparison(hash, authorization.hash)) {
            return callback(Boom.unauthorized('Bad message hash', 'Hawk'), credentials);
        }
 
        // Check nonce
 
        options.nonceFunc(authorization.nonce, authorization.ts, function (err) {
 
            if (err) {
                return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials);
            }
 
            // Check timestamp staleness
 
            if (Math.abs((authorization.ts * 1000) - now) > (options.timestampSkewSec * 1000)) {
                return callback(Boom.unauthorized('Stale timestamp'), credentials);
            }
 
            // Successful authentication
 
            return callback(null, credentials);
        });
    });
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/utils.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/lib/utils.js

Statements: 18.75% (12 / 64)      Branches: 0% (0 / 50)      Functions: 0% (0 / 9)      Lines: 18.75% (12 / 64)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166    1 1         1     1                 1     1                                           1                       1                                                       1           1               1                                                                                                                       1            
// Load modules
 
var Sntp = require('sntp');
var Boom = require('boom');
 
 
// Declare internals
 
var internals = {};
 
 
exports.version = function () {
 
    return require('../package.json').version;
};
 
 
// Extract host and port from request
 
//                                            $1                            $2
internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/;              // (IPv4, hostname)|(IPv6)
 
 
exports.parseHost = function (req, hostHeaderName) {
 
    hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host');
    var hostHeader = req.headers[hostHeaderName];
    if (!hostHeader) {
        return null;
    }
 
    var hostParts = hostHeader.match(internals.hostHeaderRegex);
    if (!hostParts) {
        return null;
    }
 
    return {
        name: hostParts[1],
        port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80))
    };
};
 
 
// Parse Content-Type header content
 
exports.parseContentType = function (header) {
 
    if (!header) {
        return '';
    }
 
    return header.split(';')[0].trim().toLowerCase();
};
 
 
// Convert node's  to request configuration object
 
exports.parseRequest = function (req, options) {
 
    if (!req.headers) {
        return req;
    }
    
    // Obtain host and port information
 
    if (!options.host || !options.port) {
        var host = exports.parseHost(req, options.hostHeaderName);
        if (!host) {
            return new Error('Invalid Host header');
        }
    }
 
    var request = {
        method: req.method,
        url: req.url,
        host: options.host || host.name,
        port: options.port || host.port,
        authorization: req.headers.authorization,
        contentType: req.headers['content-type'] || ''
    };
 
    return request;
};
 
 
exports.now = function (localtimeOffsetMsec) {
 
    return Sntp.now() + (localtimeOffsetMsec || 0);
};
 
 
exports.nowSecs = function (localtimeOffsetMsec) {
 
    return Math.floor(exports.now(localtimeOffsetMsec) / 1000);
};
 
 
// Parse Hawk HTTP Authorization header
 
exports.parseAuthorizationHeader = function (header, keys) {
 
    keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg'];
 
    if (!header) {
        return Boom.unauthorized(null, 'Hawk');
    }
 
    var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/);       // Header: scheme[ something]
    if (!headerParts) {
        return Boom.badRequest('Invalid header syntax');
    }
 
    var scheme = headerParts[1];
    if (scheme.toLowerCase() !== 'hawk') {
        return Boom.unauthorized(null, 'Hawk');
    }
 
    var attributesString = headerParts[2];
    if (!attributesString) {
        return Boom.badRequest('Invalid header syntax');
    }
 
    var attributes = {};
    var errorMessage = '';
    var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) {
 
        // Check valid attribute names
 
        if (keys.indexOf($1) === -1) {
            errorMessage = 'Unknown attribute: ' + $1;
            return;
        }
 
        // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9
 
        if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) {
            errorMessage = 'Bad attribute value: ' + $1;
            return;
        }
 
        // Check for duplicates
 
        if (attributes.hasOwnProperty($1)) {
            errorMessage = 'Duplicate attribute: ' + $1;
            return;
        }
 
        attributes[$1] = $2;
        return '';
    });
 
    if (verify !== '') {
        return Boom.badRequest(errorMessage || 'Bad header format');
    }
 
    return attributes;
};
 
 
exports.unauthorized = function (message) {
 
    return Boom.unauthorized(message, 'Hawk');
};
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
module.exports = require('./lib');
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/lib/

Statements: 27.59% (32 / 116)      Branches: 0% (0 / 50)      Functions: 0% (0 / 29)      Lines: 27.59% (32 / 116)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/lib/
File Statements Branches Functions Lines
index.js 27.59% (32 / 116) 0% (0 / 50) 0% (0 / 29) 27.59% (32 / 116)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/boom/lib/index.js

Statements: 27.59% (32 / 116)      Branches: 0% (0 / 50)      Functions: 0% (0 / 29)      Lines: 27.59% (32 / 116)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295    1 1         1     1             1                 1                                                                     1                               1           1                                                                                                                               1           1           1           1           1           1           1           1           1           1           1           1           1           1           1         1           1               1                       1           1           1           1           1              
// Load modules
 
var Http = require('http');
var Hoek = require('hoek');
 
 
// Declare internals
 
var internals = {};
 
 
exports.wrap = function (error, statusCode, message) {
 
    Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
    return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message));
};
 
 
exports.create = function (statusCode, message, data) {
 
    var error = new Error(message ? message : undefined);       // Avoids settings null message
    error.data = data || null;
    internals.initialize(error, statusCode);
    return error;
};
 
 
internals.initialize = function (error, statusCode, message) {
 
    var numberCode = parseInt(statusCode, 10);
    Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode);
 
    error.isBoom = true;
    error.isServer = numberCode >= 500;
 
    if (!error.hasOwnProperty('data')) {
        error.data = null;
    }
 
    error.output = {
        statusCode: numberCode,
        payload: {},
        headers: {}
    };
 
    error.reformat = internals.reformat;
    error.reformat();
 
    if (!message &&
        !error.message) {
 
        message = error.output.payload.error;
    }
 
    if (message) {
        error.message = (message + (error.message ? ': ' + error.message : ''));
    }
 
    return error;
};
 
 
internals.reformat = function () {
 
    this.output.payload.statusCode = this.output.statusCode;
    this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown';
 
    if (this.output.statusCode === 500) {
        this.output.payload.message = 'An internal server error occurred';              // Hide actual error from user
    }
    else if (this.message) {
        this.output.payload.message = this.message;
    }
};
 
 
// 4xx Client Errors
 
exports.badRequest = function (message, data) {
 
    return exports.create(400, message, data);
};
 
 
exports.unauthorized = function (message, scheme, attributes) {          // Or function (message, wwwAuthenticate[])
 
    var err = exports.create(401, message);
 
    if (!scheme) {
        return err;
    }
 
    var wwwAuthenticate = '';
    var i = 0;
    var il = 0;
 
    if (typeof scheme === 'string') {
 
        // function (message, scheme, attributes)
 
        wwwAuthenticate = scheme;
        if (attributes) {
            var names = Object.keys(attributes);
            for (i = 0, il = names.length; i < il; ++i) {
                if (i) {
                    wwwAuthenticate += ',';
                }
 
                var value = attributes[names[i]];
                if (value === null ||
                    value === undefined) {              // Value can be zero
 
                    value = '';
                }
                wwwAuthenticate += ' ' + names[i] + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
            }
        }
 
        if (message) {
            if (attributes) {
                wwwAuthenticate += ',';
            }
            wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
        }
        else {
            err.isMissing = true;
        }
    }
    else {
 
        // function (message, wwwAuthenticate[])
 
        var wwwArray = scheme;
        for (i = 0, il = wwwArray.length; i < il; ++i) {
            if (i) {
                wwwAuthenticate += ', ';
            }
 
            wwwAuthenticate += wwwArray[i];
        }
    }
 
    err.output.headers['WWW-Authenticate'] = wwwAuthenticate;
 
    return err;
};
 
 
exports.forbidden = function (message, data) {
 
    return exports.create(403, message, data);
};
 
 
exports.notFound = function (message, data) {
 
    return exports.create(404, message, data);
};
 
 
exports.methodNotAllowed = function (message, data) {
 
    return exports.create(405, message, data);
};
 
 
exports.notAcceptable = function (message, data) {
 
    return exports.create(406, message, data);
};
 
 
exports.proxyAuthRequired = function (message, data) {
 
    return exports.create(407, message, data);
};
 
 
exports.clientTimeout = function (message, data) {
 
    return exports.create(408, message, data);
};
 
 
exports.conflict = function (message, data) {
 
    return exports.create(409, message, data);
};
 
 
exports.resourceGone = function (message, data) {
 
    return exports.create(410, message, data);
};
 
 
exports.lengthRequired = function (message, data) {
 
    return exports.create(411, message, data);
};
 
 
exports.preconditionFailed = function (message, data) {
 
    return exports.create(412, message, data);
};
 
 
exports.entityTooLarge = function (message, data) {
 
    return exports.create(413, message, data);
};
 
 
exports.uriTooLong = function (message, data) {
 
    return exports.create(414, message, data);
};
 
 
exports.unsupportedMediaType = function (message, data) {
 
    return exports.create(415, message, data);
};
 
 
exports.rangeNotSatisfiable = function (message, data) {
 
    return exports.create(416, message, data);
};
 
 
exports.expectationFailed = function (message, data) {
 
    return exports.create(417, message, data);
};
 
exports.badData = function (message, data) {
 
    return exports.create(422, message, data);
};
 
 
exports.tooManyRequests = function (message, data) {
 
    return exports.create(429, message, data);
};
 
 
// 5xx Server Errors
 
exports.internal = function (message, data, statusCode) {
 
    var error = (data instanceof Error ? exports.wrap(data, statusCode, message) : exports.create(statusCode || 500, message));
 
    if (data instanceof Error === false) {
        error.data = data;
    }
 
    return error;
};
 
 
exports.notImplemented = function (message, data) {
 
    return exports.internal(message, data, 501);
};
 
 
exports.badGateway = function (message, data) {
 
    return exports.internal(message, data, 502);
};
 
 
exports.serverTimeout = function (message, data) {
 
    return exports.internal(message, data, 503);
};
 
 
exports.gatewayTimeout = function (message, data) {
 
    return exports.internal(message, data, 504);
};
 
 
exports.badImplementation = function (message, data) {
 
    var err = exports.internal(message, data, 500);
    err.isDeveloperError = true;
    return err;
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
module.exports = require('./lib');
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/

Statements: 22.22% (6 / 27)      Branches: 0% (0 / 14)      Functions: 0% (0 / 3)      Lines: 22.22% (6 / 27)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/
File Statements Branches Functions Lines
index.js 22.22% (6 / 27) 0% (0 / 14) 0% (0 / 3) 22.22% (6 / 27)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/cryptiles/lib/index.js

Statements: 22.22% (6 / 27)      Branches: 0% (0 / 14)      Functions: 0% (0 / 3)      Lines: 22.22% (6 / 27)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70    1 1         1         1                       1                                       1                                                
// Load modules
 
var Crypto = require('crypto');
var Boom = require('boom');
 
 
// Declare internals
 
var internals = {};
 
 
// Generate a cryptographically strong pseudo-random data
 
exports.randomString = function (size) {
 
    var buffer = exports.randomBits((size + 1) * 6);
    if (buffer instanceof Error) {
        return buffer;
    }
 
    var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
    return string.slice(0, size);
};
 
 
exports.randomBits = function (bits) {
 
    if (!bits ||
        bits < 0) {
 
        return Boom.internal('Invalid random bits count');
    }
 
    var bytes = Math.ceil(bits / 8);
    try {
        return Crypto.randomBytes(bytes);
    }
    catch (err) {
        return Boom.internal('Failed generating random bits: ' + err.message);
    }
};
 
 
// Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match)
 
exports.fixedTimeComparison = function (a, b) {
 
    if (typeof a !== 'string' ||
        typeof b !== 'string') {
 
        return false;
    }
 
    var mismatch = (a.length === b.length ? 0 : 1);
    if (mismatch) {
        b = a;
    }
 
    for (var i = 0, il = a.length; i < il; ++i) {
        var ac = a.charCodeAt(i);
        var bc = b.charCodeAt(i);
        mismatch |= (ac ^ bc);
    }
 
    return (mismatch === 0);
};
 
 
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('./lib');
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/

Statements: 13.52% (66 / 488)      Branches: 3.82% (13 / 340)      Functions: 1.69% (1 / 59)      Lines: 13.52% (66 / 488)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/
File Statements Branches Functions Lines
escape.js 29.79% (14 / 47) 48.15% (13 / 27) 14.29% (1 / 7) 29.79% (14 / 47)
index.js 11.79% (52 / 441) 0% (0 / 313) 0% (0 / 52) 11.79% (52 / 441)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/escape.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/escape.js

Statements: 29.79% (14 / 47)      Branches: 48.15% (13 / 27)      Functions: 14.29% (1 / 7)      Lines: 29.79% (14 / 47)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134    1     1                                               1                                               1                     1                               1                   1           1                           1   1   1   91                   68       1      
// Declare internals
 
var internals = {};
 
 
exports.escapeJavaScript = function (input) {
 
    if (!input) {
        return '';
    }
 
    var escaped = '';
 
    for (var i = 0, il = input.length; i < il; ++i) {
 
        var charCode = input.charCodeAt(i);
 
        if (internals.isSafe(charCode)) {
            escaped += input[i];
        }
        else {
            escaped += internals.escapeJavaScriptChar(charCode);
        }
    }
 
    return escaped;
};
 
 
exports.escapeHtml = function (input) {
 
    if (!input) {
        return '';
    }
 
    var escaped = '';
 
    for (var i = 0, il = input.length; i < il; ++i) {
 
        var charCode = input.charCodeAt(i);
 
        if (internals.isSafe(charCode)) {
            escaped += input[i];
        }
        else {
            escaped += internals.escapeHtmlChar(charCode);
        }
    }
 
    return escaped;
};
 
 
internals.escapeJavaScriptChar = function (charCode) {
 
    if (charCode >= 256) {
        return '\\u' + internals.padLeft('' + charCode, 4);
    }
 
    var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
    return '\\x' + internals.padLeft(hexValue, 2);
};
 
 
internals.escapeHtmlChar = function (charCode) {
 
    var namedEscape = internals.namedHtml[charCode];
    if (typeof namedEscape !== 'undefined') {
        return namedEscape;
    }
 
    if (charCode >= 256) {
        return '&#' + charCode + ';';
    }
 
    var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
    return '&#x' + internals.padLeft(hexValue, 2) + ';';
};
 
 
internals.padLeft = function (str, len) {
 
    while (str.length < len) {
        str = '0' + str;
    }
 
    return str;
};
 
 
internals.isSafe = function (charCode) {
 
    return (typeof internals.safeCharCodes[charCode] !== 'undefined');
};
 
 
internals.namedHtml = {
    '38': '&amp;',
    '60': '&lt;',
    '62': '&gt;',
    '34': '&quot;',
    '160': '&nbsp;',
    '162': '&cent;',
    '163': '&pound;',
    '164': '&curren;',
    '169': '&copy;',
    '174': '&reg;'
};
 
 
internals.safeCharCodes = (function () {
 
    var safe = {};
 
    for (var i = 32; i < 123; ++i) {
 
        if ((i >= 97) ||                    // a-z
            (i >= 65 && i <= 90) ||         // A-Z
            (i >= 48 && i <= 57) ||         // 0-9
            i === 32 ||                     // space
            i === 46 ||                     // .
            i === 44 ||                     // ,
            i === 45 ||                     // -
            i === 58 ||                     // :
            i === 95) {                     // _
 
            safe[i] = null;
        }
    }
 
    return safe;
}());
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/hoek/lib/index.js

Statements: 11.79% (52 / 441)      Branches: 0% (0 / 313)      Functions: 0% (0 / 52)      Lines: 11.79% (52 / 441)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979    1 1 1 1         1         1                                                                                                                                             1                                                                                                                       1                                         1                             1                               1                     1                                 1                                                 1                                                                                                                                                                                                                                     1                                       1                                               1                                                   1                                                                                                                                                                                                                                                           1                                     1                                                                 1                   1                       1                         1                                                   1               1     1                             1                                                 1             1           1           1             1           1           1                 1                 1                 1                                       1                   1           1           1                         1                                         1                                               1               1     1     1     1                                                               1                             1                     1                        
// Load modules
 
var Crypto = require('crypto');
var Path = require('path');
var Util = require('util');
var Escape = require('./escape');
 
 
// Declare internals
 
var internals = {};
 
 
// Clone object or array
 
exports.clone = function (obj, seen) {
 
    if (typeof obj !== 'object' ||
        obj === null) {
 
        return obj;
    }
 
    seen = seen || { orig: [], copy: [] };
 
    var lookup = seen.orig.indexOf(obj);
    if (lookup !== -1) {
        return seen.copy[lookup];
    }
 
    var newObj;
    var cloneDeep = false;
 
    if (!Array.isArray(obj)) {
        if (Buffer.isBuffer(obj)) {
            newObj = new Buffer(obj);
        }
        else if (obj instanceof Date) {
            newObj = new Date(obj.getTime());
        }
        else if (obj instanceof RegExp) {
            newObj = new RegExp(obj);
        }
        else {
            var proto = Object.getPrototypeOf(obj);
            if (proto &&
                proto.isImmutable) {
 
                newObj = obj;
            }
            else {
                newObj = Object.create(proto);
                cloneDeep = true;
            }
        }
    }
    else {
        newObj = [];
        cloneDeep = true;
    }
 
    seen.orig.push(obj);
    seen.copy.push(newObj);
 
    if (cloneDeep) {
        var keys = Object.getOwnPropertyNames(obj);
        for (var i = 0, il = keys.length; i < il; ++i) {
            var key = keys[i];
            var descriptor = Object.getOwnPropertyDescriptor(obj, key);
            if (descriptor.get ||
                descriptor.set) {
 
                Object.defineProperty(newObj, key, descriptor);
            }
            else {
                newObj[key] = exports.clone(obj[key], seen);
            }
        }
    }
 
    return newObj;
};
 
 
// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied
/*eslint-disable */
exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {
/*eslint-enable */
    exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
    exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
 
    if (!source) {
        return target;
    }
 
    if (Array.isArray(source)) {
        exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
        if (isMergeArrays === false) {                                                  // isMergeArrays defaults to true
            target.length = 0;                                                          // Must not change target assignment
        }
 
        for (var i = 0, il = source.length; i < il; ++i) {
            target.push(exports.clone(source[i]));
        }
 
        return target;
    }
 
    var keys = Object.keys(source);
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var value = source[key];
        if (value &&
            typeof value === 'object') {
 
            if (!target[key] ||
                typeof target[key] !== 'object' ||
                (Array.isArray(target[key]) ^ Array.isArray(value)) ||
                value instanceof Date ||
                Buffer.isBuffer(value) ||
                value instanceof RegExp) {
 
                target[key] = exports.clone(value);
            }
            else {
                exports.merge(target[key], value, isNullOverride, isMergeArrays);
            }
        }
        else {
            if (value !== null &&
                value !== undefined) {                              // Explicit to preserve empty strings
 
                target[key] = value;
            }
            else if (isNullOverride !== false) {                    // Defaults to true
                target[key] = value;
            }
        }
    }
 
    return target;
};
 
 
// Apply options to a copy of the defaults
 
exports.applyToDefaults = function (defaults, options, isNullOverride) {
 
    exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
    exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
 
    if (!options) {                                                 // If no options, return null
        return null;
    }
 
    var copy = exports.clone(defaults);
 
    if (options === true) {                                         // If options is set to true, use defaults
        return copy;
    }
 
    return exports.merge(copy, options, isNullOverride === true, false);
};
 
 
// Clone an object except for the listed keys which are shallow copied
 
exports.cloneWithShallow = function (source, keys) {
 
    if (!source ||
        typeof source !== 'object') {
 
        return source;
    }
 
    var storage = internals.store(source, keys);    // Move shallow copy items to storage
    var copy = exports.clone(source);               // Deep copy the rest
    internals.restore(copy, source, storage);       // Shallow copy the stored items and restore
    return copy;
};
 
 
internals.store = function (source, keys) {
 
    var storage = {};
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        var value = exports.reach(source, key);
        if (value !== undefined) {
            storage[key] = value;
            internals.reachSet(source, key, undefined);
        }
    }
 
    return storage;
};
 
 
internals.restore = function (copy, source, storage) {
 
    var keys = Object.keys(storage);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        internals.reachSet(copy, key, storage[key]);
        internals.reachSet(source, key, storage[key]);
    }
};
 
 
internals.reachSet = function (obj, key, value) {
 
    var path = key.split('.');
    var ref = obj;
    for (var i = 0, il = path.length; i < il; ++i) {
        var segment = path[i];
        if (i + 1 === il) {
            ref[segment] = value;
        }
 
        ref = ref[segment];
    }
};
 
 
// Apply options to defaults except for the listed keys which are shallow copied from option without merging
 
exports.applyToDefaultsWithShallow = function (defaults, options, keys) {
 
    exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
    exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
    exports.assert(keys && Array.isArray(keys), 'Invalid keys');
 
    if (!options) {                                                 // If no options, return null
        return null;
    }
 
    var copy = exports.cloneWithShallow(defaults, keys);
 
    if (options === true) {                                         // If options is set to true, use defaults
        return copy;
    }
 
    var storage = internals.store(options, keys);   // Move shallow copy items to storage
    exports.merge(copy, options, false, false);     // Deep copy the rest
    internals.restore(copy, options, storage);      // Shallow copy the stored items and restore
    return copy;
};
 
 
// Deep object or array comparison
 
exports.deepEqual = function (obj, ref, options, seen) {
 
    options = options || { prototype: true };
 
    var type = typeof obj;
 
    if (type !== typeof ref) {
        return false;
    }
 
    if (type !== 'object' ||
        obj === null ||
        ref === null) {
 
        if (obj === ref) {                                                      // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql
            return obj !== 0 || 1 / obj === 1 / ref;        // -0 / +0
        }
 
        return obj !== obj && ref !== ref;                  // NaN
    }
 
    seen = seen || [];
    if (seen.indexOf(obj) !== -1) {
        return true;                            // If previous comparison failed, it would have stopped execution
    }
 
    seen.push(obj);
 
    if (Array.isArray(obj)) {
        if (!Array.isArray(ref)) {
            return false;
        }
 
        if (!options.part && obj.length !== ref.length) {
            return false;
        }
 
        for (var i = 0, il = obj.length; i < il; ++i) {
            if (options.part) {
                var found = false;
                for (var r = 0, rl = ref.length; r < rl; ++r) {
                    if (exports.deepEqual(obj[i], ref[r], options, seen)) {
                        found = true;
                        break;
                    }
                }
 
                return found;
            }
 
            if (!exports.deepEqual(obj[i], ref[i], options, seen)) {
                return false;
            }
        }
 
        return true;
    }
 
    if (Buffer.isBuffer(obj)) {
        if (!Buffer.isBuffer(ref)) {
            return false;
        }
 
        if (obj.length !== ref.length) {
            return false;
        }
 
        for (var j = 0, jl = obj.length; j < jl; ++j) {
            if (obj[j] !== ref[j]) {
                return false;
            }
        }
 
        return true;
    }
 
    if (obj instanceof Date) {
        return (ref instanceof Date && obj.getTime() === ref.getTime());
    }
 
    if (obj instanceof RegExp) {
        return (ref instanceof RegExp && obj.toString() === ref.toString());
    }
 
    if (options.prototype) {
        if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
            return false;
        }
    }
 
    var keys = Object.getOwnPropertyNames(obj);
 
    if (!options.part && keys.length !== Object.getOwnPropertyNames(ref).length) {
        return false;
    }
 
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var descriptor = Object.getOwnPropertyDescriptor(obj, key);
        if (descriptor.get) {
            if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) {
                return false;
            }
        }
        else if (!exports.deepEqual(obj[key], ref[key], options, seen)) {
            return false;
        }
    }
 
    return true;
};
 
 
// Remove duplicate items from array
 
exports.unique = function (array, key) {
 
    var index = {};
    var result = [];
 
    for (var i = 0, il = array.length; i < il; ++i) {
        var id = (key ? array[i][key] : array[i]);
        if (index[id] !== true) {
 
            result.push(array[i]);
            index[id] = true;
        }
    }
 
    return result;
};
 
 
// Convert array into object
 
exports.mapToObject = function (array, key) {
 
    if (!array) {
        return null;
    }
 
    var obj = {};
    for (var i = 0, il = array.length; i < il; ++i) {
        if (key) {
            if (array[i][key]) {
                obj[array[i][key]] = true;
            }
        }
        else {
            obj[array[i]] = true;
        }
    }
 
    return obj;
};
 
 
// Find the common unique items in two arrays
 
exports.intersect = function (array1, array2, justFirst) {
 
    if (!array1 || !array2) {
        return [];
    }
 
    var common = [];
    var hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1);
    var found = {};
    for (var i = 0, il = array2.length; i < il; ++i) {
        if (hash[array2[i]] && !found[array2[i]]) {
            if (justFirst) {
                return array2[i];
            }
 
            common.push(array2[i]);
            found[array2[i]] = true;
        }
    }
 
    return (justFirst ? null : common);
};
 
 
// Test if the reference contains the values
 
exports.contain = function (ref, values, options) {
 
    /*
        string -> string(s)
        array -> item(s)
        object -> key(s)
        object -> object (key:value)
    */
 
    var valuePairs = null;
    if (typeof ref === 'object' &&
        typeof values === 'object' &&
        !Array.isArray(ref) &&
        !Array.isArray(values)) {
 
        valuePairs = values;
        values = Object.keys(values);
    }
    else {
        values = [].concat(values);
    }
 
    options = options || {};            // deep, once, only, part
 
    exports.assert(arguments.length >= 2, 'Insufficient arguments');
    exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
    exports.assert(values.length, 'Values array cannot be empty');
 
    var compare, compareFlags;
    if (options.deep) {
        compare = exports.deepEqual;
 
        var hasOnly = options.hasOwnProperty('only'), hasPart = options.hasOwnProperty('part');
 
        compareFlags = {
            prototype: hasOnly ? options.only : hasPart ? !options.part : false,
            part: hasOnly ? !options.only : hasPart ? options.part : true
        };
    }
    else {
        compare = function (a, b) {
 
            return a === b;
        };
    }
 
    var misses = false;
    var matches = new Array(values.length);
    for (var i = 0, il = matches.length; i < il; ++i) {
        matches[i] = 0;
    }
 
    if (typeof ref === 'string') {
        var pattern = '(';
        for (i = 0, il = values.length; i < il; ++i) {
            var value = values[i];
            exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
            pattern += (i ? '|' : '') + exports.escapeRegex(value);
        }
 
        var regex = new RegExp(pattern + ')', 'g');
        var leftovers = ref.replace(regex, function ($0, $1) {
 
            var index = values.indexOf($1);
            ++matches[index];
            return '';          // Remove from string
        });
 
        misses = !!leftovers;
    }
    else if (Array.isArray(ref)) {
        for (i = 0, il = ref.length; i < il; ++i) {
            for (var j = 0, jl = values.length, matched = false; j < jl && matched === false; ++j) {
                matched = compare(values[j], ref[i], compareFlags) && j;
            }
 
            if (matched !== false) {
                ++matches[matched];
            }
            else {
                misses = true;
            }
        }
    }
    else {
        var keys = Object.keys(ref);
        for (i = 0, il = keys.length; i < il; ++i) {
            var key = keys[i];
            var pos = values.indexOf(key);
            if (pos !== -1) {
                if (valuePairs &&
                    !compare(valuePairs[key], ref[key], compareFlags)) {
 
                    return false;
                }
 
                ++matches[pos];
            }
            else {
                misses = true;
            }
        }
    }
 
    var result = false;
    for (i = 0, il = matches.length; i < il; ++i) {
        result = result || !!matches[i];
        if ((options.once && matches[i] > 1) ||
            (!options.part && !matches[i])) {
 
            return false;
        }
    }
 
    if (options.only &&
        misses) {
 
        return false;
    }
 
    return result;
};
 
 
// Flatten array
 
exports.flatten = function (array, target) {
 
    var result = target || [];
 
    for (var i = 0, il = array.length; i < il; ++i) {
        if (Array.isArray(array[i])) {
            exports.flatten(array[i], result);
        }
        else {
            result.push(array[i]);
        }
    }
 
    return result;
};
 
 
// Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
 
exports.reach = function (obj, chain, options) {
 
    options = options || {};
    if (typeof options === 'string') {
        options = { separator: options };
    }
 
    var path = chain.split(options.separator || '.');
    var ref = obj;
    for (var i = 0, il = path.length; i < il; ++i) {
        var key = path[i];
        if (key[0] === '-' && Array.isArray(ref)) {
            key = key.slice(1, key.length);
            key = ref.length - key;
        }
 
        if (!ref ||
            !ref.hasOwnProperty(key) ||
            (typeof ref !== 'object' && options.functions === false)) {         // Only object and function can have properties
 
            exports.assert(!options.strict || i + 1 === il, 'Missing segment', key, 'in reach path ', chain);
            exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
            ref = options.default;
            break;
        }
 
        ref = ref[key];
    }
 
    return ref;
};
 
 
exports.reachTemplate = function (obj, template, options) {
 
    return template.replace(/{([^}]+)}/g, function ($0, chain) {
 
        var value = exports.reach(obj, chain, options);
        return (value === undefined || value === null ? '' : value);
    });
};
 
 
exports.formatStack = function (stack) {
 
    var trace = [];
    for (var i = 0, il = stack.length; i < il; ++i) {
        var item = stack[i];
        trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
    }
 
    return trace;
};
 
 
exports.formatTrace = function (trace) {
 
    var display = [];
 
    for (var i = 0, il = trace.length; i < il; ++i) {
        var row = trace[i];
        display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
    }
 
    return display;
};
 
 
exports.callStack = function (slice) {
 
    // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
 
    var v8 = Error.prepareStackTrace;
    Error.prepareStackTrace = function (err, stack) {
 
        return stack;
    };
 
    var capture = {};
    Error.captureStackTrace(capture, arguments.callee);     /*eslint no-caller:0 */
    var stack = capture.stack;
 
    Error.prepareStackTrace = v8;
 
    var trace = exports.formatStack(stack);
 
    if (slice) {
        return trace.slice(slice);
    }
 
    return trace;
};
 
 
exports.displayStack = function (slice) {
 
    var trace = exports.callStack(slice === undefined ? 1 : slice + 1);
 
    return exports.formatTrace(trace);
};
 
 
exports.abortThrow = false;
 
 
exports.abort = function (message, hideStack) {
 
    if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
        throw new Error(message || 'Unknown error');
    }
 
    var stack = '';
    if (!hideStack) {
        stack = exports.displayStack(1).join('\n\t');
    }
    console.log('ABORT: ' + message + '\n\t' + stack);
    process.exit(1);
};
 
 
exports.assert = function (condition /*, msg1, msg2, msg3 */) {
 
    if (condition) {
        return;
    }
 
    if (arguments.length === 2 && arguments[1] instanceof Error) {
        throw arguments[1];
    }
 
    var msgs = [];
    for (var i = 1, il = arguments.length; i < il; ++i) {
        if (arguments[i] !== '') {
            msgs.push(arguments[i]);            // Avoids Array.slice arguments leak, allowing for V8 optimizations
        }
    }
 
    msgs = msgs.map(function (msg) {
 
        return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg);
    });
    throw new Error(msgs.join(' ') || 'Unknown error');
};
 
 
exports.Timer = function () {
 
    this.ts = 0;
    this.reset();
};
 
 
exports.Timer.prototype.reset = function () {
 
    this.ts = Date.now();
};
 
 
exports.Timer.prototype.elapsed = function () {
 
    return Date.now() - this.ts;
};
 
 
exports.Bench = function () {
 
    this.ts = 0;
    this.reset();
};
 
 
exports.Bench.prototype.reset = function () {
 
    this.ts = exports.Bench.now();
};
 
 
exports.Bench.prototype.elapsed = function () {
 
    return exports.Bench.now() - this.ts;
};
 
 
exports.Bench.now = function () {
 
    var ts = process.hrtime();
    return (ts[0] * 1e3) + (ts[1] / 1e6);
};
 
 
// Escape string for Regex construction
 
exports.escapeRegex = function (string) {
 
    // Escape ^$.*+-?=!:|\/()[]{},
    return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
};
 
 
// Base64url (RFC 4648) encode
 
exports.base64urlEncode = function (value, encoding) {
 
    var buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary'));
    return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
 
 
// Base64url (RFC 4648) decode
 
exports.base64urlDecode = function (value, encoding) {
 
    if (value &&
        !/^[\w\-]*$/.test(value)) {
 
        return new Error('Invalid character');
    }
 
    try {
        var buf = new Buffer(value, 'base64');
        return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
    }
    catch (err) {
        return err;
    }
};
 
 
// Escape attribute value for use in HTTP header
 
exports.escapeHeaderAttribute = function (attribute) {
 
    // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
 
    exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
 
    return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');                             // Escape quotes and slash
};
 
 
exports.escapeHtml = function (string) {
 
    return Escape.escapeHtml(string);
};
 
 
exports.escapeJavaScript = function (string) {
 
    return Escape.escapeJavaScript(string);
};
 
 
exports.nextTick = function (callback) {
 
    return function () {
 
        var args = arguments;
        process.nextTick(function () {
 
            callback.apply(null, args);
        });
    };
};
 
 
exports.once = function (method) {
 
    if (method._hoekOnce) {
        return method;
    }
 
    var once = false;
    var wrapped = function () {
 
        if (!once) {
            once = true;
            method.apply(null, arguments);
        }
    };
 
    wrapped._hoekOnce = true;
 
    return wrapped;
};
 
 
exports.isAbsolutePath = function (path, platform) {
 
    if (!path) {
        return false;
    }
 
    if (Path.isAbsolute) {                      // node >= 0.11
        return Path.isAbsolute(path);
    }
 
    platform = platform || process.platform;
 
    // Unix
 
    if (platform !== 'win32') {
        return path[0] === '/';
    }
 
    // Windows
 
    return !!/^(?:[a-zA-Z]:[\\\/])|(?:[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/])/.test(path);        // C:\ or \\something\something
};
 
 
exports.isInteger = function (value) {
 
    return (typeof value === 'number' &&
            parseFloat(value) === parseInt(value, 10) &&
            !isNaN(value));
};
 
 
exports.ignore = function () { };
 
 
exports.inherits = Util.inherits;
 
 
exports.format = Util.format;
 
 
exports.transform = function (source, transform, options) {
 
    exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source object: must be null, undefined, or an object');
 
    var result = {};
    var keys = Object.keys(transform);
 
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var path = key.split('.');
        var sourcePath = transform[key];
 
        exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings');
 
        var segment;
        var res = result;
 
        while (path.length > 1) {
            segment = path.shift();
            if (!res[segment]) {
                res[segment] = {};
            }
            res = res[segment];
        }
        segment = path.shift();
        res[segment] = exports.reach(source, sourcePath, options);
    }
 
    return result;
};
 
 
exports.uniqueFilename = function (path, extension) {
 
    if (extension) {
        extension = extension[0] !== '.' ? '.' + extension : extension;
    }
    else {
        extension = '';
    }
 
    path = Path.resolve(path);
    var name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
    return Path.join(path, name);
};
 
 
exports.stringify = function () {
 
    try {
        return JSON.stringify.apply(null, arguments);
    }
    catch (err) {
        return '[Cannot display object: ' + err.message + ']';
    }
};
 
 
exports.shallow = function (source) {
 
    var target = {};
    var keys = Object.keys(source);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        target[key] = source[key];
    }
 
    return target;
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 21  
module.exports = require('./lib');
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/lib/

Statements: 9.09% (16 / 176)      Branches: 0% (0 / 83)      Functions: 0% (0 / 22)      Lines: 9.64% (16 / 166)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/lib/
File Statements Branches Functions Lines
index.js 9.09% (16 / 176) 0% (0 / 83) 0% (0 / 22) 9.64% (16 / 166)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/hawk/node_modules/sntp/lib/index.js

Statements: 9.09% (16 / 176)      Branches: 0% (0 / 83)      Functions: 0% (0 / 22)      Lines: 9.64% (16 / 166)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414    1 1 1         1     1                                                                                                                                                                                                                                                                   1                                                                                                                                                                                                                                         1                                 1                                     1               1                                                                                     1         1                                                       1                     1           1                         1        
// Load modules
 
var Dgram = require('dgram');
var Dns = require('dns');
var Hoek = require('hoek');
 
 
// Declare internals
 
var internals = {};
 
 
exports.time = function (options, callback) {
 
    if (arguments.length !== 2) {
        callback = arguments[0];
        options = {};
    }
 
    var settings = Hoek.clone(options);
    settings.host = settings.host || 'pool.ntp.org';
    settings.port = settings.port || 123;
    settings.resolveReference = settings.resolveReference || false;
 
    // Declare variables used by callback
 
    var timeoutId = 0;
    var sent = 0;
 
    // Ensure callback is only called once
 
    var finish = function (err, result) {
 
        if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = 0;
        }
 
        socket.removeAllListeners();
        socket.once('error', internals.ignore);
        socket.close();
        return callback(err, result);
    };
 
    finish = Hoek.once(finish);
 
    // Create UDP socket
 
    var socket = Dgram.createSocket('udp4');
 
    socket.once('error', function (err) {
 
        return finish(err);
    });
 
    // Listen to incoming messages
 
    socket.on('message', function (buffer, rinfo) {
 
        var received = Date.now();
 
        var message = new internals.NtpMessage(buffer);
        if (!message.isValid) {
            return finish(new Error('Invalid server response'), message);
        }
 
        if (message.originateTimestamp !== sent) {
            return finish(new Error('Wrong originate timestamp'), message);
        }
 
        // Timestamp Name          ID   When Generated
        // ------------------------------------------------------------
        // Originate Timestamp     T1   time request sent by client
        // Receive Timestamp       T2   time request received by server
        // Transmit Timestamp      T3   time reply sent by server
        // Destination Timestamp   T4   time reply received by client
        //
        // The roundtrip delay d and system clock offset t are defined as:
        //
        // d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2
 
        var T1 = message.originateTimestamp;
        var T2 = message.receiveTimestamp;
        var T3 = message.transmitTimestamp;
        var T4 = received;
 
        message.d = (T4 - T1) - (T3 - T2);
        message.t = ((T2 - T1) + (T3 - T4)) / 2;
        message.receivedLocally = received;
 
        if (!settings.resolveReference ||
            message.stratum !== 'secondary') {
 
            return finish(null, message);
        }
 
        // Resolve reference IP address
 
        Dns.reverse(message.referenceId, function (err, domains) {
 
            if (/* $lab:coverage:off$ */ !err /* $lab:coverage:on$ */) {
                message.referenceHost = domains[0];
            }
 
            return finish(null, message);
        });
    });
 
    // Set timeout
 
    if (settings.timeout) {
        timeoutId = setTimeout(function () {
 
            timeoutId = 0;
            return finish(new Error('Timeout'));
        }, settings.timeout);
    }
 
    // Construct NTP message
 
    var message = new Buffer(48);
    for (var i = 0; i < 48; i++) {                      // Zero message
        message[i] = 0;
    }
 
    message[0] = (0 << 6) + (4 << 3) + (3 << 0)         // Set version number to 4 and Mode to 3 (client)
    sent = Date.now();
    internals.fromMsecs(sent, message, 40);               // Set transmit timestamp (returns as originate)
 
    // Send NTP request
 
    socket.send(message, 0, message.length, settings.port, settings.host, function (err, bytes) {
 
        if (err ||
            bytes !== 48) {
 
            return finish(err || new Error('Could not send entire message'));
        }
    });
};
 
 
internals.NtpMessage = function (buffer) {
 
    this.isValid = false;
 
    // Validate
 
    if (buffer.length !== 48) {
        return;
    }
 
    // Leap indicator
 
    var li = (buffer[0] >> 6);
    switch (li) {
        case 0: this.leapIndicator = 'no-warning'; break;
        case 1: this.leapIndicator = 'last-minute-61'; break;
        case 2: this.leapIndicator = 'last-minute-59'; break;
        case 3: this.leapIndicator = 'alarm'; break;
    }
 
    // Version
 
    var vn = ((buffer[0] & 0x38) >> 3);
    this.version = vn;
 
    // Mode
 
    var mode = (buffer[0] & 0x7);
    switch (mode) {
        case 1: this.mode = 'symmetric-active'; break;
        case 2: this.mode = 'symmetric-passive'; break;
        case 3: this.mode = 'client'; break;
        case 4: this.mode = 'server'; break;
        case 5: this.mode = 'broadcast'; break;
        case 0:
        case 6:
        case 7: this.mode = 'reserved'; break;
    }
 
    // Stratum
 
    var stratum = buffer[1];
    if (stratum === 0) {
        this.stratum = 'death';
    }
    else if (stratum === 1) {
        this.stratum = 'primary';
    }
    else if (stratum <= 15) {
        this.stratum = 'secondary';
    }
    else {
        this.stratum = 'reserved';
    }
 
    // Poll interval (msec)
 
    this.pollInterval = Math.round(Math.pow(2, buffer[2])) * 1000;
 
    // Precision (msecs)
 
    this.precision = Math.pow(2, buffer[3]) * 1000;
 
    // Root delay (msecs)
 
    var rootDelay = 256 * (256 * (256 * buffer[4] + buffer[5]) + buffer[6]) + buffer[7];
    this.rootDelay = 1000 * (rootDelay / 0x10000);
 
    // Root dispersion (msecs)
 
    this.rootDispersion = ((buffer[8] << 8) + buffer[9] + ((buffer[10] << 8) + buffer[11]) / Math.pow(2, 16)) * 1000;
 
    // Reference identifier
 
    this.referenceId = '';
    switch (this.stratum) {
        case 'death':
        case 'primary':
            this.referenceId = String.fromCharCode(buffer[12]) + String.fromCharCode(buffer[13]) + String.fromCharCode(buffer[14]) + String.fromCharCode(buffer[15]);
            break;
        case 'secondary':
            this.referenceId = '' + buffer[12] + '.' + buffer[13] + '.' + buffer[14] + '.' + buffer[15];
            break;
    }
 
    // Reference timestamp
 
    this.referenceTimestamp = internals.toMsecs(buffer, 16);
 
    // Originate timestamp
 
    this.originateTimestamp = internals.toMsecs(buffer, 24);
 
    // Receive timestamp
 
    this.receiveTimestamp = internals.toMsecs(buffer, 32);
 
    // Transmit timestamp
 
    this.transmitTimestamp = internals.toMsecs(buffer, 40);
 
    // Validate
 
    if (this.version === 4 &&
        this.stratum !== 'reserved' &&
        this.mode === 'server' &&
        this.originateTimestamp &&
        this.receiveTimestamp &&
        this.transmitTimestamp) {
 
        this.isValid = true;
    }
 
    return this;
};
 
 
internals.toMsecs = function (buffer, offset) {
 
    var seconds = 0;
    var fraction = 0;
 
    for (var i = 0; i < 4; ++i) {
        seconds = (seconds * 256) + buffer[offset + i];
    }
 
    for (i = 4; i < 8; ++i) {
        fraction = (fraction * 256) + buffer[offset + i];
    }
 
    return ((seconds - 2208988800 + (fraction / Math.pow(2, 32))) * 1000);
};
 
 
internals.fromMsecs = function (ts, buffer, offset) {
 
    var seconds = Math.floor(ts / 1000) + 2208988800;
    var fraction = Math.round((ts % 1000) / 1000 * Math.pow(2, 32));
 
    buffer[offset + 0] = (seconds & 0xFF000000) >> 24;
    buffer[offset + 1] = (seconds & 0x00FF0000) >> 16;
    buffer[offset + 2] = (seconds & 0x0000FF00) >> 8;
    buffer[offset + 3] = (seconds & 0x000000FF);
 
    buffer[offset + 4] = (fraction & 0xFF000000) >> 24;
    buffer[offset + 5] = (fraction & 0x00FF0000) >> 16;
    buffer[offset + 6] = (fraction & 0x0000FF00) >> 8;
    buffer[offset + 7] = (fraction & 0x000000FF);
};
 
 
// Offset singleton
 
internals.last = {
    offset: 0,
    expires: 0,
    host: '',
    port: 0
};
 
 
exports.offset = function (options, callback) {
 
    if (arguments.length !== 2) {
        callback = arguments[0];
        options = {};
    }
 
    var now = Date.now();
    var clockSyncRefresh = options.clockSyncRefresh || 24 * 60 * 60 * 1000;                    // Daily
 
    if (internals.last.offset &&
        internals.last.host === options.host &&
        internals.last.port === options.port &&
        now < internals.last.expires) {
 
        process.nextTick(function () {
 
            callback(null, internals.last.offset);
        });
 
        return;
    }
 
    exports.time(options, function (err, time) {
 
        if (err) {
            return callback(err, 0);
        }
 
        internals.last = {
            offset: Math.round(time.t),
            expires: now + clockSyncRefresh,
            host: options.host,
            port: options.port
        };
 
        return callback(null, internals.last.offset);
    });
};
 
 
// Now singleton
 
internals.now = {
    intervalId: 0
};
 
 
exports.start = function (options, callback) {
 
    if (arguments.length !== 2) {
        callback = arguments[0];
        options = {};
    }
 
    if (internals.now.intervalId) {
        process.nextTick(function () {
 
            callback();
        });
 
        return;
    }
 
    exports.offset(options, function (err, offset) {
 
        internals.now.intervalId = setInterval(function () {
 
            exports.offset(options, function () { });
        }, options.clockSyncRefresh || 24 * 60 * 60 * 1000);                                // Daily
 
        return callback();
    });
};
 
 
exports.stop = function () {
 
    if (!internals.now.intervalId) {
        return;
    }
 
    clearInterval(internals.now.intervalId);
    internals.now.intervalId = 0;
};
 
 
exports.isLive = function () {
 
    return !!internals.now.intervalId;
};
 
 
exports.now = function () {
 
    var now = Date.now();
    if (!exports.isLive() ||
        now >= internals.last.expires) {
 
        return now;
    }
 
    return now + internals.last.offset;
};
 
 
internals.ignore = function () {
 
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/

Statements: 11.86% (46 / 388)      Branches: 0% (0 / 135)      Functions: 0% (0 / 23)      Lines: 12.07% (46 / 381)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/
File Statements Branches Functions Lines
index.js 100% (5 / 5) 100% (0 / 0) 100% (0 / 0) 100% (5 / 5)
parser.js 13.01% (16 / 123) 0% (0 / 78) 0% (0 / 9) 13.11% (16 / 122)
signer.js 19.12% (13 / 68) 0% (0 / 22) 0% (0 / 5) 19.12% (13 / 68)
util.js 5.2% (9 / 173) 0% (0 / 27) 0% (0 / 7) 5.39% (9 / 167)
verify.js 15.79% (3 / 19) 0% (0 / 8) 0% (0 / 2) 15.79% (3 / 19)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/index.js

Statements: 100% (5 / 5)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (5 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29    1 1 1 1           1                                  
// Copyright 2015 Joyent, Inc.
 
var parser = require('./parser');
var signer = require('./signer');
var verify = require('./verify');
var util = require('./util');
 
 
 
///--- API
 
module.exports = {
 
  parse: parser.parseRequest,
  parseRequest: parser.parseRequest,
 
  sign: signer.signRequest,
  signRequest: signer.signRequest,
 
  sshKeyToPEM: util.sshKeyToPEM,
  sshKeyFingerprint: util.fingerprint,
  pemToRsaSSHKey: util.pemToRsaSSHKey,
 
  verify: verify.verifySignature,
  verifySignature: verify.verifySignature,
  verifyHMAC: verify.verifyHMAC
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/parser.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/parser.js

Statements: 13.01% (16 / 123)      Branches: 0% (0 / 78)      Functions: 0% (0 / 9)      Lines: 13.11% (16 / 122)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306    1 1           1                   1         1                     1             1   1     1     1     1     1     1     1     1           1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
// Copyright 2012 Joyent, Inc.  All rights reserved.
 
var assert = require('assert-plus');
var util = require('util');
 
 
 
///--- Globals
 
var Algorithms = {
  'rsa-sha1': true,
  'rsa-sha256': true,
  'rsa-sha512': true,
  'dsa-sha1': true,
  'hmac-sha1': true,
  'hmac-sha256': true,
  'hmac-sha512': true
};
 
var State = {
  New: 0,
  Params: 1
};
 
var ParamsState = {
  Name: 0,
  Quote: 1,
  Value: 2,
  Comma: 3
};
 
 
 
///--- Specific Errors
 
function HttpSignatureError(message, caller) {
  if (Error.captureStackTrace)
    Error.captureStackTrace(this, caller || HttpSignatureError);
 
  this.message = message;
  this.name = caller.name;
}
util.inherits(HttpSignatureError, Error);
 
function ExpiredRequestError(message) {
  HttpSignatureError.call(this, message, ExpiredRequestError);
}
util.inherits(ExpiredRequestError, HttpSignatureError);
 
 
function InvalidHeaderError(message) {
  HttpSignatureError.call(this, message, InvalidHeaderError);
}
util.inherits(InvalidHeaderError, HttpSignatureError);
 
 
function InvalidParamsError(message) {
  HttpSignatureError.call(this, message, InvalidParamsError);
}
util.inherits(InvalidParamsError, HttpSignatureError);
 
 
function MissingHeaderError(message) {
  HttpSignatureError.call(this, message, MissingHeaderError);
}
util.inherits(MissingHeaderError, HttpSignatureError);
 
 
 
///--- Exported API
 
module.exports = {
 
  /**
   * Parses the 'Authorization' header out of an http.ServerRequest object.
   *
   * Note that this API will fully validate the Authorization header, and throw
   * on any error.  It will not however check the signature, or the keyId format
   * as those are specific to your environment.  You can use the options object
   * to pass in extra constraints.
   *
   * As a response object you can expect this:
   *
   *     {
   *       "scheme": "Signature",
   *       "params": {
   *         "keyId": "foo",
   *         "algorithm": "rsa-sha256",
   *         "headers": [
   *           "date" or "x-date",
   *           "content-md5"
   *         ],
   *         "signature": "base64"
   *       },
   *       "signingString": "ready to be passed to crypto.verify()"
   *     }
   *
   * @param {Object} request an http.ServerRequest.
   * @param {Object} options an optional options object with:
   *                   - clockSkew: allowed clock skew in seconds (default 300).
   *                   - headers: required header names (def: date or x-date)
   *                   - algorithms: algorithms to support (default: all).
   * @return {Object} parsed out object (see above).
   * @throws {TypeError} on invalid input.
   * @throws {InvalidHeaderError} on an invalid Authorization header error.
   * @throws {InvalidParamsError} if the params in the scheme are invalid.
   * @throws {MissingHeaderError} if the params indicate a header not present,
   *                              either in the request headers from the params,
   *                              or not in the params from a required header
   *                              in options.
   * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
   */
  parseRequest: function parseRequest(request, options) {
    assert.object(request, 'request');
    assert.object(request.headers, 'request.headers');
    if (options === undefined) {
      options = {};
    }
    if (options.headers === undefined) {
      options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
    }
    assert.object(options, 'options');
    assert.arrayOfString(options.headers, 'options.headers');
    assert.optionalNumber(options.clockSkew, 'options.clockSkew');
 
    if (!request.headers.authorization)
      throw new MissingHeaderError('no authorization header present in ' +
                                   'the request');
 
    options.clockSkew = options.clockSkew || 300;
 
 
    var i = 0;
    var state = State.New;
    var substate = ParamsState.Name;
    var tmpName = '';
    var tmpValue = '';
 
    var parsed = {
      scheme: '',
      params: {},
      signingString: '',
 
      get algorithm() {
        return this.params.algorithm.toUpperCase();
      },
 
      get keyId() {
        return this.params.keyId;
      }
 
    };
 
    var authz = request.headers.authorization;
    for (i = 0; i < authz.length; i++) {
      var c = authz.charAt(i);
 
      switch (Number(state)) {
 
      case State.New:
        if (c !== ' ') parsed.scheme += c;
        else state = State.Params;
        break;
 
      case State.Params:
        switch (Number(substate)) {
 
        case ParamsState.Name:
          var code = c.charCodeAt(0);
          // restricted name of A-Z / a-z
          if ((code >= 0x41 && code <= 0x5a) || // A-Z
              (code >= 0x61 && code <= 0x7a)) { // a-z
            tmpName += c;
          } else if (c === '=') {
            if (tmpName.length === 0)
              throw new InvalidHeaderError('bad param format');
            substate = ParamsState.Quote;
          } else {
            throw new InvalidHeaderError('bad param format');
          }
          break;
 
        case ParamsState.Quote:
          if (c === '"') {
            tmpValue = '';
            substate = ParamsState.Value;
          } else {
            throw new InvalidHeaderError('bad param format');
          }
          break;
 
        case ParamsState.Value:
          if (c === '"') {
            parsed.params[tmpName] = tmpValue;
            substate = ParamsState.Comma;
          } else {
            tmpValue += c;
          }
          break;
 
        case ParamsState.Comma:
          if (c === ',') {
            tmpName = '';
            substate = ParamsState.Name;
          } else {
            throw new InvalidHeaderError('bad param format');
          }
          break;
 
        default:
          throw new Error('Invalid substate');
        }
        break;
 
      default:
        throw new Error('Invalid substate');
      }
 
    }
 
    if (!parsed.params.headers || parsed.params.headers === '') {
      if (request.headers['x-date']) {
        parsed.params.headers = ['x-date'];
      } else {
        parsed.params.headers = ['date'];
      }
    } else {
      parsed.params.headers = parsed.params.headers.split(' ');
    }
 
    // Minimally validate the parsed object
    if (!parsed.scheme || parsed.scheme !== 'Signature')
      throw new InvalidHeaderError('scheme was not "Signature"');
 
    if (!parsed.params.keyId)
      throw new InvalidHeaderError('keyId was not specified');
 
    if (!parsed.params.algorithm)
      throw new InvalidHeaderError('algorithm was not specified');
 
    if (!parsed.params.signature)
      throw new InvalidHeaderError('signature was not specified');
 
    // Check the algorithm against the official list
    parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
    if (!Algorithms[parsed.params.algorithm])
      throw new InvalidParamsError(parsed.params.algorithm +
                                   ' is not supported');
 
    // Build the signingString
    for (i = 0; i < parsed.params.headers.length; i++) {
      var h = parsed.params.headers[i].toLowerCase();
      parsed.params.headers[i] = h;
 
      if (h !== 'request-line') {
        var value = request.headers[h];
        if (!value)
          throw new MissingHeaderError(h + ' was not in the request');
        parsed.signingString += h + ': ' + value;
      } else {
        parsed.signingString +=
          request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
      }
 
      if ((i + 1) < parsed.params.headers.length)
        parsed.signingString += '\n';
    }
 
    // Check against the constraints
    var date;
    if (request.headers.date || request.headers['x-date']) {
        if (request.headers['x-date']) {
          date = new Date(request.headers['x-date']);
        } else {
          date = new Date(request.headers.date);
        }
      var now = new Date();
      var skew = Math.abs(now.getTime() - date.getTime());
 
      if (skew > options.clockSkew * 1000) {
        throw new ExpiredRequestError('clock skew of ' +
                                      (skew / 1000) +
                                      's was greater than ' +
                                      options.clockSkew + 's');
      }
    }
 
    options.headers.forEach(function (hdr) {
      // Remember that we already checked any headers in the params
      // were in the request, so if this passes we're good.
      if (parsed.params.headers.indexOf(hdr) < 0)
        throw new MissingHeaderError(hdr + ' was not a signed header');
    });
 
    if (options.algorithms) {
      if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
        throw new InvalidParamsError(parsed.params.algorithm +
                                     ' is not a supported algorithm');
    }
 
    return parsed;
  }
 
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/signer.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/signer.js

Statements: 19.12% (13 / 68)      Branches: 0% (0 / 22)      Functions: 0% (0 / 5)      Lines: 19.12% (13 / 68)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180    1 1 1   1           1                   1             1         1     1         1           1               1                                                           1                                                                                                                                                                                          
// Copyright 2012 Joyent, Inc.  All rights reserved.
 
var assert = require('assert-plus');
var crypto = require('crypto');
var http = require('http');
 
var sprintf = require('util').format;
 
 
 
///--- Globals
 
var Algorithms = {
  'rsa-sha1': true,
  'rsa-sha256': true,
  'rsa-sha512': true,
  'dsa-sha1': true,
  'hmac-sha1': true,
  'hmac-sha256': true,
  'hmac-sha512': true
};
 
var Authorization =
  'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
 
 
 
///--- Specific Errors
 
function MissingHeaderError(message) {
    this.name = 'MissingHeaderError';
    this.message = message;
    this.stack = (new Error()).stack;
}
MissingHeaderError.prototype = new Error();
 
 
function InvalidAlgorithmError(message) {
    this.name = 'InvalidAlgorithmError';
    this.message = message;
    this.stack = (new Error()).stack;
}
InvalidAlgorithmError.prototype = new Error();
 
 
 
///--- Internal Functions
 
function _pad(val) {
  if (parseInt(val, 10) < 10) {
    val = '0' + val;
  }
  return val;
}
 
 
function _rfc1123() {
  var date = new Date();
 
  var months = ['Jan',
                'Feb',
                'Mar',
                'Apr',
                'May',
                'Jun',
                'Jul',
                'Aug',
                'Sep',
                'Oct',
                'Nov',
                'Dec'];
  var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  return days[date.getUTCDay()] + ', ' +
    _pad(date.getUTCDate()) + ' ' +
    months[date.getUTCMonth()] + ' ' +
    date.getUTCFullYear() + ' ' +
    _pad(date.getUTCHours()) + ':' +
    _pad(date.getUTCMinutes()) + ':' +
    _pad(date.getUTCSeconds()) +
    ' GMT';
}
 
 
 
///--- Exported API
 
module.exports = {
 
  /**
   * Adds an 'Authorization' header to an http.ClientRequest object.
   *
   * Note that this API will add a Date header if it's not already set. Any
   * other headers in the options.headers array MUST be present, or this
   * will throw.
   *
   * You shouldn't need to check the return type; it's just there if you want
   * to be pedantic.
   *
   * @param {Object} request an instance of http.ClientRequest.
   * @param {Object} options signing parameters object:
   *                   - {String} keyId required.
   *                   - {String} key required (either a PEM or HMAC key).
   *                   - {Array} headers optional; defaults to ['date'].
   *                   - {String} algorithm optional; defaults to 'rsa-sha256'.
   *                   - {String} httpVersion optional; defaults to '1.1'.
   * @return {Boolean} true if Authorization (and optionally Date) were added.
   * @throws {TypeError} on bad parameter types (input).
   * @throws {InvalidAlgorithmError} if algorithm was bad.
   * @throws {MissingHeaderError} if a header to be signed was specified but
   *                              was not present.
   */
  signRequest: function signRequest(request, options) {
    assert.object(request, 'request');
    assert.object(options, 'options');
    assert.optionalString(options.algorithm, 'options.algorithm');
    assert.string(options.keyId, 'options.keyId');
    assert.optionalArrayOfString(options.headers, 'options.headers');
    assert.optionalString(options.httpVersion, 'options.httpVersion');
 
    if (!request.getHeader('Date'))
      request.setHeader('Date', _rfc1123());
    if (!options.headers)
      options.headers = ['date'];
    if (!options.algorithm)
      options.algorithm = 'rsa-sha256';
    if (!options.httpVersion)
      options.httpVersion = '1.1';
 
    options.algorithm = options.algorithm.toLowerCase();
 
    if (!Algorithms[options.algorithm])
      throw new InvalidAlgorithmError(options.algorithm + ' is not supported');
 
    var i;
    var stringToSign = '';
    for (i = 0; i < options.headers.length; i++) {
      if (typeof (options.headers[i]) !== 'string')
        throw new TypeError('options.headers must be an array of Strings');
 
      var h = options.headers[i].toLowerCase();
 
      if (h !== 'request-line') {
        var value = request.getHeader(h);
        if (!value) {
          throw new MissingHeaderError(h + ' was not in the request');
        }
        stringToSign += h + ': ' + value;
      } else {
        stringToSign +=
          request.method + ' ' + request.path + ' HTTP/' + options.httpVersion;
      }
 
      if ((i + 1) < options.headers.length)
        stringToSign += '\n';
    }
 
    var alg = options.algorithm.match(/(hmac|rsa)-(\w+)/);
    var signature;
    if (alg[1] === 'hmac') {
      var hmac = crypto.createHmac(alg[2].toUpperCase(), options.key);
      hmac.update(stringToSign);
      signature = hmac.digest('base64');
    } else {
      var signer = crypto.createSign(options.algorithm.toUpperCase());
      signer.update(stringToSign);
      signature = signer.sign(options.key, 'base64');
    }
 
    request.setHeader('Authorization', sprintf(Authorization,
                                               options.keyId,
                                               options.algorithm,
                                               options.headers.join(' '),
                                               signature));
 
    return true;
  }
 
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/util.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/util.js

Statements: 5.2% (9 / 173)      Branches: 0% (0 / 27)      Functions: 0% (0 / 7)      Lines: 5.39% (9 / 167)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308    1 1   1 1           1                         1                     1                                                                                                                                         1                                                                                                                                                                   1                                                                                                                                                                                                                                                
// Copyright 2012 Joyent, Inc.  All rights reserved.
 
var assert = require('assert-plus');
var crypto = require('crypto');
 
var asn1 = require('asn1');
var ctype = require('ctype');
 
 
 
///--- Helpers
 
function readNext(buffer, offset) {
  var len = ctype.ruint32(buffer, 'big', offset);
  offset += 4;
 
  var newOffset = offset + len;
 
  return {
    data: buffer.slice(offset, newOffset),
    offset: newOffset
  };
}
 
 
function writeInt(writer, buffer) {
  writer.writeByte(0x02); // ASN1.Integer
  writer.writeLength(buffer.length);
 
  for (var i = 0; i < buffer.length; i++)
    writer.writeByte(buffer[i]);
 
  return writer;
}
 
 
function rsaToPEM(key) {
  var buffer;
  var der;
  var exponent;
  var i;
  var modulus;
  var newKey = '';
  var offset = 0;
  var type;
  var tmp;
 
  try {
    buffer = new Buffer(key.split(' ')[1], 'base64');
 
    tmp = readNext(buffer, offset);
    type = tmp.data.toString();
    offset = tmp.offset;
 
    if (type !== 'ssh-rsa')
      throw new Error('Invalid ssh key type: ' + type);
 
    tmp = readNext(buffer, offset);
    exponent = tmp.data;
    offset = tmp.offset;
 
    tmp = readNext(buffer, offset);
    modulus = tmp.data;
  } catch (e) {
    throw new Error('Invalid ssh key: ' + key);
  }
 
  // DER is a subset of BER
  der = new asn1.BerWriter();
 
  der.startSequence();
 
  der.startSequence();
  der.writeOID('1.2.840.113549.1.1.1');
  der.writeNull();
  der.endSequence();
 
  der.startSequence(0x03); // bit string
  der.writeByte(0x00);
 
  // Actual key
  der.startSequence();
  writeInt(der, modulus);
  writeInt(der, exponent);
  der.endSequence();
 
  // bit string
  der.endSequence();
 
  der.endSequence();
 
  tmp = der.buffer.toString('base64');
  for (i = 0; i < tmp.length; i++) {
    if ((i % 64) === 0)
      newKey += '\n';
    newKey += tmp.charAt(i);
  }
 
  if (!/\\n$/.test(newKey))
    newKey += '\n';
 
  return '-----BEGIN PUBLIC KEY-----' + newKey + '-----END PUBLIC KEY-----\n';
}
 
 
function dsaToPEM(key) {
  var buffer;
  var offset = 0;
  var tmp;
  var der;
  var newKey = '';
 
  var type;
  var p;
  var q;
  var g;
  var y;
 
  try {
    buffer = new Buffer(key.split(' ')[1], 'base64');
 
    tmp = readNext(buffer, offset);
    type = tmp.data.toString();
    offset = tmp.offset;
 
    /* JSSTYLED */
    if (!/^ssh-ds[as].*/.test(type))
      throw new Error('Invalid ssh key type: ' + type);
 
    tmp = readNext(buffer, offset);
    p = tmp.data;
    offset = tmp.offset;
 
    tmp = readNext(buffer, offset);
    q = tmp.data;
    offset = tmp.offset;
 
    tmp = readNext(buffer, offset);
    g = tmp.data;
    offset = tmp.offset;
 
    tmp = readNext(buffer, offset);
    y = tmp.data;
  } catch (e) {
    console.log(e.stack);
    throw new Error('Invalid ssh key: ' + key);
  }
 
  // DER is a subset of BER
  der = new asn1.BerWriter();
 
  der.startSequence();
 
  der.startSequence();
  der.writeOID('1.2.840.10040.4.1');
 
  der.startSequence();
  writeInt(der, p);
  writeInt(der, q);
  writeInt(der, g);
  der.endSequence();
 
  der.endSequence();
 
  der.startSequence(0x03); // bit string
  der.writeByte(0x00);
  writeInt(der, y);
  der.endSequence();
 
  der.endSequence();
 
  tmp = der.buffer.toString('base64');
  for (var i = 0; i < tmp.length; i++) {
    if ((i % 64) === 0)
      newKey += '\n';
    newKey += tmp.charAt(i);
  }
 
  if (!/\\n$/.test(newKey))
    newKey += '\n';
 
  return '-----BEGIN PUBLIC KEY-----' + newKey + '-----END PUBLIC KEY-----\n';
}
 
 
///--- API
 
module.exports = {
 
  /**
   * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
   *
   * The intent of this module is to interoperate with OpenSSL only,
   * specifically the node crypto module's `verify` method.
   *
   * @param {String} key an OpenSSH public key.
   * @return {String} PEM encoded form of the RSA public key.
   * @throws {TypeError} on bad input.
   * @throws {Error} on invalid ssh key formatted data.
   */
  sshKeyToPEM: function sshKeyToPEM(key) {
    assert.string(key, 'ssh_key');
 
    /* JSSTYLED */
    if (/^ssh-rsa.*/.test(key))
      return rsaToPEM(key);
 
    /* JSSTYLED */
    if (/^ssh-ds[as].*/.test(key))
      return dsaToPEM(key);
 
    throw new Error('Only RSA and DSA public keys are allowed');
  },
 
 
  /**
   * Generates an OpenSSH fingerprint from an ssh public key.
   *
   * @param {String} key an OpenSSH public key.
   * @return {String} key fingerprint.
   * @throws {TypeError} on bad input.
   * @throws {Error} if what you passed doesn't look like an ssh public key.
   */
  fingerprint: function fingerprint(key) {
    assert.string(key, 'ssh_key');
 
    var pieces = key.split(' ');
    if (!pieces || !pieces.length || pieces.length < 2)
      throw new Error('invalid ssh key');
 
    var data = new Buffer(pieces[1], 'base64');
 
    var hash = crypto.createHash('md5');
    hash.update(data);
    var digest = hash.digest('hex');
 
    var fp = '';
    for (var i = 0; i < digest.length; i++) {
      if (i && i % 2 === 0)
        fp += ':';
 
      fp += digest[i];
    }
 
    return fp;
  },
 
  /**
   * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
   *
   * The reverse of the above function.
   */
  pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
    assert.equal('string', typeof (pem), 'typeof pem');
 
    // chop off the BEGIN PUBLIC KEY and END PUBLIC KEY portion
    var cleaned = pem.split('\n').slice(1, -2).join('');
 
    var buf = new Buffer(cleaned, 'base64');
 
    var der = new asn1.BerReader(buf);
 
    der.readSequence();
    der.readSequence();
 
    var oid = der.readOID();
    assert.equal(oid, '1.2.840.113549.1.1.1', 'pem not in RSA format');
 
    // Null -- XXX this probably isn't good practice
    der.readByte();
    der.readByte();
 
    // bit string sequence
    der.readSequence(0x03);
    der.readByte();
    der.readSequence();
 
    // modulus
    assert.equal(der.peek(), asn1.Ber.Integer, 'modulus not an integer');
    der._offset = der.readLength(der.offset + 1);
    var modulus = der._buf.slice(der.offset, der.offset + der.length);
    der._offset += der.length;
 
    // exponent
    assert.equal(der.peek(), asn1.Ber.Integer, 'exponent not an integer');
    der._offset = der.readLength(der.offset + 1);
    var exponent = der._buf.slice(der.offset, der.offset + der.length);
    der._offset += der.length;
 
    // now, make the key
    var type = new Buffer('ssh-rsa');
    var buffer = new Buffer(4 + type.length + 4 + modulus.length +
      4 + exponent.length);
    var i = 0;
    buffer.writeUInt32BE(type.length, i);     i += 4;
    type.copy(buffer, i);                     i += type.length;
    buffer.writeUInt32BE(exponent.length, i); i += 4;
    exponent.copy(buffer, i);                 i += exponent.length;
    buffer.writeUInt32BE(modulus.length, i);  i += 4;
    modulus.copy(buffer, i);                  i += modulus.length;
 
    var s = (type.toString() + ' ' + buffer.toString('base64') + ' ' +
      (comment || ''));
    return s;
  }
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/verify.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/lib/verify.js

Statements: 15.79% (3 / 19)      Branches: 0% (0 / 8)      Functions: 0% (0 / 2)      Lines: 15.79% (3 / 19)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58    1 1           1                                                                                                
// Copyright 2015 Joyent, Inc.
 
var assert = require('assert-plus');
var crypto = require('crypto');
 
 
 
///--- Exported API
 
module.exports = {
  /**
   * Verify RSA/DSA signature against public key.  You are expected to pass in
   * an object that was returned from `parse()`.
   *
   * @param {Object} parsedSignature the object you got from `parse`.
   * @param {String} pubkey RSA/DSA private key PEM.
   * @return {Boolean} true if valid, false otherwise.
   * @throws {TypeError} if you pass in bad arguments.
   */
  verifySignature: function verifySignature(parsedSignature, pubkey) {
    assert.object(parsedSignature, 'parsedSignature');
    assert.string(pubkey, 'pubkey');
 
    var alg = parsedSignature.algorithm.match(/^(RSA|DSA)-(\w+)/);
    if (!alg || alg.length !== 3)
      throw new TypeError('parsedSignature: unsupported algorithm ' +
                          parsedSignature.algorithm);
 
    var verify = crypto.createVerify(alg[0]);
    verify.update(parsedSignature.signingString);
    return verify.verify(pubkey, parsedSignature.params.signature, 'base64');
  },
 
  /**
   * Verify HMAC against shared secret.  You are expected to pass in an object
   * that was returned from `parse()`.
   *
   * @param {Object} parsedSignature the object you got from `parse`.
   * @param {String} secret HMAC shared secret.
   * @return {Boolean} true if valid, false otherwise.
   * @throws {TypeError} if you pass in bad arguments.
   */
  verifyHMAC: function verifyHMAC(parsedSignature, secret) {
    assert.object(parsedSignature, 'parsedHMAC');
    assert.string(secret, 'secret');
 
    var alg = parsedSignature.algorithm.match(/^HMAC-(\w+)/);
    if (!alg || alg.length !== 2)
      throw new TypeError('parsedSignature: unsupported algorithm ' +
                          parsedSignature.algorithm);
 
    var hmac = crypto.createHmac(alg[1].toUpperCase(), secret);
    hmac.update(parsedSignature.signingString);
    return (hmac.digest('base64') === parsedSignature.params.signature);
  }
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/
File Statements Branches Functions Lines
index.js 100% (2 / 2) 100% (0 / 0) 100% (0 / 0) 100% (2 / 2)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/index.js

Statements: 100% (2 / 2)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (2 / 2)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22          1           1                    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
// If you have no idea what ASN.1 or BER is, see this:
// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
 
var Ber = require('./ber/index');
 
 
 
///--- Exported API
 
module.exports = {
 
  Ber: Ber,
 
  BerReader: Ber.Reader,
 
  BerWriter: Ber.Writer
 
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/

Statements: 14.61% (52 / 356)      Branches: 1.29% (2 / 155)      Functions: 0% (0 / 38)      Lines: 14.69% (52 / 354)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/
File Statements Branches Functions Lines
errors.js 20% (1 / 5) 0% (0 / 2) 0% (0 / 1) 20% (1 / 5)
index.js 100% (11 / 11) 50% (2 / 4) 100% (0 / 0) 100% (11 / 11)
reader.js 11.59% (16 / 138) 0% (0 / 70) 0% (0 / 15) 11.76% (16 / 136)
types.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
writer.js 11.44% (23 / 201) 0% (0 / 79) 0% (0 / 22) 11.44% (23 / 201)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/errors.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/errors.js

Statements: 20% (1 / 5)      Branches: 0% (0 / 2)      Functions: 0% (0 / 1)      Lines: 20% (1 / 5)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15      1                      
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
 
module.exports = {
 
  newInvalidAsn1Error: function(msg) {
    var e = new Error();
    e.name = 'InvalidAsn1Error';
    e.message = msg || '';
    return e;
  }
 
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/index.js

Statements: 100% (11 / 11)      Branches: 50% (2 / 4)      Functions: 100% (0 / 0)      Lines: 100% (11 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29    1 1   1 1         1               1 31 31   1 1 1      
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
var errors = require('./errors');
var types = require('./types');
 
var Reader = require('./reader');
var Writer = require('./writer');
 
 
///--- Exports
 
module.exports = {
 
  Reader: Reader,
 
  Writer: Writer
 
};
 
for (var t in types) {
  Eif (types.hasOwnProperty(t))
    module.exports[t] = types[t];
}
for (var e in errors) {
  Eif (errors.hasOwnProperty(e))
    module.exports[e] = errors[e];
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/reader.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/reader.js

Statements: 11.59% (16 / 138)      Branches: 0% (0 / 70)      Functions: 0% (0 / 15)      Lines: 11.76% (16 / 136)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269    1   1 1         1           1                                                           1                         1                               1                                                                                     1                                 1         1         1         1                                                             1                                                                                     1                                                                                   1    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
var assert = require('assert');
 
var ASN1 = require('./types');
var errors = require('./errors');
 
 
///--- Globals
 
var newInvalidAsn1Error = errors.newInvalidAsn1Error;
 
 
 
///--- API
 
function Reader(data) {
  if (!data || !Buffer.isBuffer(data))
    throw new TypeError('data must be a node Buffer');
 
  this._buf = data;
  this._size = data.length;
 
  // These hold the "current" state
  this._len = 0;
  this._offset = 0;
 
  var self = this;
  this.__defineGetter__('length', function() { return self._len; });
  this.__defineGetter__('offset', function() { return self._offset; });
  this.__defineGetter__('remain', function() {
    return self._size - self._offset;
  });
  this.__defineGetter__('buffer', function() {
    return self._buf.slice(self._offset);
  });
}
 
 
/**
 * Reads a single byte and advances offset; you can pass in `true` to make this
 * a "peek" operation (i.e., get the byte, but don't advance the offset).
 *
 * @param {Boolean} peek true means don't move offset.
 * @return {Number} the next byte, null if not enough data.
 */
Reader.prototype.readByte = function(peek) {
  if (this._size - this._offset < 1)
    return null;
 
  var b = this._buf[this._offset] & 0xff;
 
  if (!peek)
    this._offset += 1;
 
  return b;
};
 
 
Reader.prototype.peek = function() {
  return this.readByte(true);
};
 
 
/**
 * Reads a (potentially) variable length off the BER buffer.  This call is
 * not really meant to be called directly, as callers have to manipulate
 * the internal buffer afterwards.
 *
 * As a result of this call, you can call `Reader.length`, until the
 * next thing called that does a readLength.
 *
 * @return {Number} the amount of offset to advance the buffer.
 * @throws {InvalidAsn1Error} on bad ASN.1
 */
Reader.prototype.readLength = function(offset) {
  if (offset === undefined)
    offset = this._offset;
 
  if (offset >= this._size)
    return null;
 
  var lenB = this._buf[offset++] & 0xff;
  if (lenB === null)
    return null;
 
  if ((lenB & 0x80) == 0x80) {
    lenB &= 0x7f;
 
    if (lenB == 0)
      throw newInvalidAsn1Error('Indefinite length not supported');
 
    if (lenB > 4)
      throw newInvalidAsn1Error('encoding too long');
 
    if (this._size - offset < lenB)
      return null;
 
    this._len = 0;
    for (var i = 0; i < lenB; i++)
      this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
 
  } else {
    // Wasn't a variable length
    this._len = lenB;
  }
 
  return offset;
};
 
 
/**
 * Parses the next sequence in this BER buffer.
 *
 * To get the length of the sequence, call `Reader.length`.
 *
 * @return {Number} the sequence's tag.
 */
Reader.prototype.readSequence = function(tag) {
  var seq = this.peek();
  if (seq === null)
    return null;
  if (tag !== undefined && tag !== seq)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + seq.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
  if (o === null)
    return null;
 
  this._offset = o;
  return seq;
};
 
 
Reader.prototype.readInt = function() {
  return this._readTag(ASN1.Integer);
};
 
 
Reader.prototype.readBoolean = function() {
  return (this._readTag(ASN1.Boolean) === 0 ? false : true);
};
 
 
Reader.prototype.readEnumeration = function() {
  return this._readTag(ASN1.Enumeration);
};
 
 
Reader.prototype.readString = function(tag, retbuf) {
  if (!tag)
    tag = ASN1.OctetString;
 
  var b = this.peek();
  if (b === null)
    return null;
 
  if (b !== tag)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + b.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
 
  if (o === null)
    return null;
 
  if (this.length > this._size - o)
    return null;
 
  this._offset = o;
 
  if (this.length === 0)
    return '';
 
  var str = this._buf.slice(this._offset, this._offset + this.length);
  this._offset += this.length;
 
  return retbuf ? str : str.toString('utf8');
};
 
Reader.prototype.readOID = function(tag) {
  if (!tag)
    tag = ASN1.OID;
 
  var b = this.peek();
  if (b === null)
    return null;
 
  if (b !== tag)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + b.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
  if (o === null)
    return null;
 
  if (this.length > this._size - o)
    return null;
 
  this._offset = o;
 
  var values = [];
  var value = 0;
 
  for (var i = 0; i < this.length; i++) {
    var byte = this._buf[this._offset++] & 0xff;
 
    value <<= 7;
    value += byte & 0x7f;
    if ((byte & 0x80) == 0) {
      values.push(value);
      value = 0;
    }
  }
 
  value = values.shift();
  values.unshift(value % 40);
  values.unshift((value / 40) >> 0);
 
  return values.join('.');
};
 
 
Reader.prototype._readTag = function(tag) {
  assert.ok(tag !== undefined);
 
  var b = this.peek();
 
  if (b === null)
    return null;
 
  if (b !== tag)
    throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
                              ': got 0x' + b.toString(16));
 
  var o = this.readLength(this._offset + 1); // stored in `length`
  if (o === null)
    return null;
 
  if (this.length > 4)
    throw newInvalidAsn1Error('Integer too long: ' + this.length);
 
  if (this.length > this._size - o)
    return null;
  this._offset = o;
 
  var fb = this._buf[this._offset++];
  var value = 0;
 
  value = fb & 0x7F;
  for (var i = 1; i < this.length; i++) {
    value <<= 8;
    value |= (this._buf[this._offset++] & 0xff);
  }
 
  if ((fb & 0x80) == 0x80)
    value = -value;
 
  return value;
};
 
 
 
///--- Exported API
 
module.exports = Reader;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/types.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/types.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38      1                                                                    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
 
module.exports = {
  EOC: 0,
  Boolean: 1,
  Integer: 2,
  BitString: 3,
  OctetString: 4,
  Null: 5,
  OID: 6,
  ObjectDescriptor: 7,
  External: 8,
  Real: 9, // float
  Enumeration: 10,
  PDV: 11,
  Utf8String: 12,
  RelativeOID: 13,
  Sequence: 16,
  Set: 17,
  NumericString: 18,
  PrintableString: 19,
  T61String: 20,
  VideotexString: 21,
  IA5String: 22,
  UTCTime: 23,
  GeneralizedTime: 24,
  GraphicString: 25,
  VisibleString: 26,
  GeneralString: 28,
  UniversalString: 29,
  CharacterString: 30,
  BMPString: 31,
  Constructor: 32,
  Context: 128
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/writer.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/asn1/lib/ber/writer.js

Statements: 11.44% (23 / 201)      Branches: 0% (0 / 79)      Functions: 0% (0 / 22)      Lines: 11.44% (23 / 201)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319    1 1 1         1   1               1                                           1                                           1                 1                                                         1           1                   1                         1                                 1                           1                     1                 1                                                                                 1                                                   1                     1                                                       1                 1                                       1    
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
 
var assert = require('assert');
var ASN1 = require('./types');
var errors = require('./errors');
 
 
///--- Globals
 
var newInvalidAsn1Error = errors.newInvalidAsn1Error;
 
var DEFAULT_OPTS = {
  size: 1024,
  growthFactor: 8
};
 
 
///--- Helpers
 
function merge(from, to) {
  assert.ok(from);
  assert.equal(typeof(from), 'object');
  assert.ok(to);
  assert.equal(typeof(to), 'object');
 
  var keys = Object.getOwnPropertyNames(from);
  keys.forEach(function(key) {
    if (to[key])
      return;
 
    var value = Object.getOwnPropertyDescriptor(from, key);
    Object.defineProperty(to, key, value);
  });
 
  return to;
}
 
 
 
///--- API
 
function Writer(options) {
  options = merge(DEFAULT_OPTS, options || {});
 
  this._buf = new Buffer(options.size || 1024);
  this._size = this._buf.length;
  this._offset = 0;
  this._options = options;
 
  // A list of offsets in the buffer where we need to insert
  // sequence tag/len pairs.
  this._seq = [];
 
  var self = this;
  this.__defineGetter__('buffer', function() {
    if (self._seq.length)
      throw new InvalidAsn1Error(self._seq.length + ' unended sequence(s)');
 
    return self._buf.slice(0, self._offset);
  });
}
 
 
Writer.prototype.writeByte = function(b) {
  if (typeof(b) !== 'number')
    throw new TypeError('argument must be a Number');
 
  this._ensure(1);
  this._buf[this._offset++] = b;
};
 
 
Writer.prototype.writeInt = function(i, tag) {
  if (typeof(i) !== 'number')
    throw new TypeError('argument must be a Number');
  if (typeof(tag) !== 'number')
    tag = ASN1.Integer;
 
  var sz = 4;
 
  while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000)) &&
         (sz > 1)) {
    sz--;
    i <<= 8;
  }
 
  if (sz > 4)
    throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff');
 
  this._ensure(2 + sz);
  this._buf[this._offset++] = tag;
  this._buf[this._offset++] = sz;
 
  while (sz-- > 0) {
    this._buf[this._offset++] = ((i & 0xff000000) >> 24);
    i <<= 8;
  }
 
};
 
 
Writer.prototype.writeNull = function() {
  this.writeByte(ASN1.Null);
  this.writeByte(0x00);
};
 
 
Writer.prototype.writeEnumeration = function(i, tag) {
  if (typeof(i) !== 'number')
    throw new TypeError('argument must be a Number');
  if (typeof(tag) !== 'number')
    tag = ASN1.Enumeration;
 
  return this.writeInt(i, tag);
};
 
 
Writer.prototype.writeBoolean = function(b, tag) {
  if (typeof(b) !== 'boolean')
    throw new TypeError('argument must be a Boolean');
  if (typeof(tag) !== 'number')
    tag = ASN1.Boolean;
 
  this._ensure(3);
  this._buf[this._offset++] = tag;
  this._buf[this._offset++] = 0x01;
  this._buf[this._offset++] = b ? 0xff : 0x00;
};
 
 
Writer.prototype.writeString = function(s, tag) {
  if (typeof(s) !== 'string')
    throw new TypeError('argument must be a string (was: ' + typeof(s) + ')');
  if (typeof(tag) !== 'number')
    tag = ASN1.OctetString;
 
  var len = Buffer.byteLength(s);
  this.writeByte(tag);
  this.writeLength(len);
  if (len) {
    this._ensure(len);
    this._buf.write(s, this._offset);
    this._offset += len;
  }
};
 
 
Writer.prototype.writeBuffer = function(buf, tag) {
  if (typeof(tag) !== 'number')
    throw new TypeError('tag must be a number');
  if (!Buffer.isBuffer(buf))
    throw new TypeError('argument must be a buffer');
 
  this.writeByte(tag);
  this.writeLength(buf.length);
  this._ensure(buf.length);
  buf.copy(this._buf, this._offset, 0, buf.length);
  this._offset += buf.length;
};
 
 
Writer.prototype.writeStringArray = function(strings) {
  if ((!strings instanceof Array))
    throw new TypeError('argument must be an Array[String]');
 
  var self = this;
  strings.forEach(function(s) {
    self.writeString(s);
  });
};
 
// This is really to solve DER cases, but whatever for now
Writer.prototype.writeOID = function(s, tag) {
  if (typeof(s) !== 'string')
    throw new TypeError('argument must be a string');
  if (typeof(tag) !== 'number')
    tag = ASN1.OID;
 
  if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
    throw new Error('argument is not a valid OID string');
 
  function encodeOctet(bytes, octet) {
    if (octet < 128) {
        bytes.push(octet);
    } else if (octet < 16384) {
        bytes.push((octet >>> 7) | 0x80);
        bytes.push(octet & 0x7F);
    } else if (octet < 2097152) {
      bytes.push((octet >>> 14) | 0x80);
      bytes.push(((octet >>> 7) | 0x80) & 0xFF);
      bytes.push(octet & 0x7F);
    } else if (octet < 268435456) {
      bytes.push((octet >>> 21) | 0x80);
      bytes.push(((octet >>> 14) | 0x80) & 0xFF);
      bytes.push(((octet >>> 7) | 0x80) & 0xFF);
      bytes.push(octet & 0x7F);
    } else {
      bytes.push(((octet >>> 28) | 0x80) & 0xFF);
      bytes.push(((octet >>> 21) | 0x80) & 0xFF);
      bytes.push(((octet >>> 14) | 0x80) & 0xFF);
      bytes.push(((octet >>> 7) | 0x80) & 0xFF);
      bytes.push(octet & 0x7F);
    }
  }
 
  var tmp = s.split('.');
  var bytes = [];
  bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
  tmp.slice(2).forEach(function(b) {
    encodeOctet(bytes, parseInt(b, 10));
  });
 
  var self = this;
  this._ensure(2 + bytes.length);
  this.writeByte(tag);
  this.writeLength(bytes.length);
  bytes.forEach(function(b) {
    self.writeByte(b);
  });
};
 
 
Writer.prototype.writeLength = function(len) {
  if (typeof(len) !== 'number')
    throw new TypeError('argument must be a Number');
 
  this._ensure(4);
 
  if (len <= 0x7f) {
    this._buf[this._offset++] = len;
  } else if (len <= 0xff) {
    this._buf[this._offset++] = 0x81;
    this._buf[this._offset++] = len;
  } else if (len <= 0xffff) {
    this._buf[this._offset++] = 0x82;
    this._buf[this._offset++] = len >> 8;
    this._buf[this._offset++] = len;
  } else if (len <= 0xffffff) {
    this._shift(start, len, 1);
    this._buf[this._offset++] = 0x83;
    this._buf[this._offset++] = len >> 16;
    this._buf[this._offset++] = len >> 8;
    this._buf[this._offset++] = len;
  } else {
    throw new InvalidAsn1ERror('Length too long (> 4 bytes)');
  }
};
 
Writer.prototype.startSequence = function(tag) {
  if (typeof(tag) !== 'number')
    tag = ASN1.Sequence | ASN1.Constructor;
 
  this.writeByte(tag);
  this._seq.push(this._offset);
  this._ensure(3);
  this._offset += 3;
};
 
 
Writer.prototype.endSequence = function() {
  var seq = this._seq.pop();
  var start = seq + 3;
  var len = this._offset - start;
 
  if (len <= 0x7f) {
    this._shift(start, len, -2);
    this._buf[seq] = len;
  } else if (len <= 0xff) {
    this._shift(start, len, -1);
    this._buf[seq] = 0x81;
    this._buf[seq + 1] = len;
  } else if (len <= 0xffff) {
    this._buf[seq] = 0x82;
    this._buf[seq + 1] = len >> 8;
    this._buf[seq + 2] = len;
  } else if (len <= 0xffffff) {
    this._shift(start, len, 1);
    this._buf[seq] = 0x83;
    this._buf[seq + 1] = len >> 16;
    this._buf[seq + 2] = len >> 8;
    this._buf[seq + 3] = len;
  } else {
    throw new InvalidAsn1Error('Sequence too long');
  }
};
 
 
Writer.prototype._shift = function(start, len, shift) {
  assert.ok(start !== undefined);
  assert.ok(len !== undefined);
  assert.ok(shift);
 
  this._buf.copy(this._buf, start + shift, start, start + len);
  this._offset += shift;
};
 
Writer.prototype._ensure = function(len) {
  assert.ok(len);
 
  if (this._size - this._offset < len) {
    var sz = this._size * this._options.growthFactor;
    if (sz - this._offset < len)
      sz += len;
 
    var buf = new Buffer(sz);
 
    this._buf.copy(buf, 0, 0, this._offset);
    this._buf = buf;
    this._size = sz;
  }
};
 
 
 
///--- Exported API
 
module.exports = Writer;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/assert-plus/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/assert-plus/

Statements: 55.43% (51 / 92)      Branches: 26.23% (16 / 61)      Functions: 20.83% (5 / 24)      Lines: 55.43% (51 / 92)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/assert-plus/
File Statements Branches Functions Lines
assert.js 55.43% (51 / 92) 26.23% (16 / 61) 20.83% (5 / 24) 55.43% (51 / 92)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/assert-plus/assert.js

Statements: 55.43% (51 / 92)      Branches: 26.23% (16 / 61)      Functions: 20.83% (5 / 24)      Lines: 55.43% (51 / 92)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247    1 1 1           1 1           1 1           1 28     1 19     1         1                                     1                                 1               1                                         1         1                         1         1                           1         1         1       1         1         1                               1                           1 10 1   9   9 1 9 1 9         1 19 19 19 2 19 2   19 9           10                   1 14 1 1     13              
// Copyright (c) 2012, Mark Cavage. All rights reserved.
 
var assert = require('assert');
var Stream = require('stream').Stream;
var util = require('util');
 
 
 
///--- Globals
 
var NDEBUG = process.env.NODE_NDEBUG || false;
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
 
 
 
///--- Messages
 
var ARRAY_TYPE_REQUIRED = '%s ([%s]) required';
var TYPE_REQUIRED = '%s (%s) is required';
 
 
 
///--- Internal
 
function capitalize(str) {
        return (str.charAt(0).toUpperCase() + str.slice(1));
}
 
function uncapitalize(str) {
        return (str.charAt(0).toLowerCase() + str.slice(1));
}
 
function _() {
        return (util.format.apply(util, arguments));
}
 
 
function _assert(arg, type, name, stackFunc) {
        if (!NDEBUG) {
                name = name || type;
                stackFunc = stackFunc || _assert.caller;
                var t = typeof (arg);
 
                if (t !== type) {
                        throw new assert.AssertionError({
                                message: _(TYPE_REQUIRED, name, type),
                                actual: t,
                                expected: type,
                                operator: '===',
                                stackStartFunction: stackFunc
                        });
                }
        }
}
 
 
function _instanceof(arg, type, name, stackFunc) {
        if (!NDEBUG) {
                name = name || type;
                stackFunc = stackFunc || _instanceof.caller;
 
                if (!(arg instanceof type)) {
                        throw new assert.AssertionError({
                                message: _(TYPE_REQUIRED, name, type.name),
                                actual: _getClass(arg),
                                expected: type.name,
                                operator: 'instanceof',
                                stackStartFunction: stackFunc
                        });
                }
        }
}
 
function _getClass(object) {
        return (Object.prototype.toString.call(object).slice(8, -1));
};
 
 
 
///--- API
 
function array(arr, type, name) {
        if (!NDEBUG) {
                name = name || type;
 
                if (!Array.isArray(arr)) {
                        throw new assert.AssertionError({
                                message: _(ARRAY_TYPE_REQUIRED, name, type),
                                actual: typeof (arr),
                                expected: 'array',
                                operator: 'Array.isArray',
                                stackStartFunction: array.caller
                        });
                }
 
                for (var i = 0; i < arr.length; i++) {
                        _assert(arr[i], type, name, array);
                }
        }
}
 
 
function bool(arg, name) {
        _assert(arg, 'boolean', name, bool);
}
 
 
function buffer(arg, name) {
        if (!Buffer.isBuffer(arg)) {
                throw new assert.AssertionError({
                        message: _(TYPE_REQUIRED, name || '', 'Buffer'),
                        actual: typeof (arg),
                        expected: 'buffer',
                        operator: 'Buffer.isBuffer',
                        stackStartFunction: buffer
                });
        }
}
 
 
function func(arg, name) {
        _assert(arg, 'function', name);
}
 
 
function number(arg, name) {
        _assert(arg, 'number', name);
        if (!NDEBUG && (isNaN(arg) || !isFinite(arg))) {
                throw new assert.AssertionError({
                        message: _(TYPE_REQUIRED, name, 'number'),
                        actual: arg,
                        expected: 'number',
                        operator: 'isNaN',
                        stackStartFunction: number
                });
        }
}
 
 
function object(arg, name) {
        _assert(arg, 'object', name);
}
 
 
function stream(arg, name) {
        _instanceof(arg, Stream, name);
}
 
 
function date(arg, name) {
        _instanceof(arg, Date, name);
}
 
function regexp(arg, name) {
        _instanceof(arg, RegExp, name);
}
 
 
function string(arg, name) {
        _assert(arg, 'string', name);
}
 
 
function uuid(arg, name) {
        string(arg, name);
        if (!NDEBUG && !UUID_REGEXP.test(arg)) {
                throw new assert.AssertionError({
                        message: _(TYPE_REQUIRED, name, 'uuid'),
                        actual: 'string',
                        expected: 'uuid',
                        operator: 'test',
                        stackStartFunction: uuid
                });
        }
}
 
 
///--- Exports
 
module.exports = {
        bool: bool,
        buffer: buffer,
        date: date,
        func: func,
        number: number,
        object: object,
        regexp: regexp,
        stream: stream,
        string: string,
        uuid: uuid
};
 
 
Object.keys(module.exports).forEach(function (k) {
        if (k === 'buffer')
                return;
 
        var name = 'arrayOf' + capitalize(k);
 
        if (k === 'bool')
                k = 'boolean';
        if (k === 'func')
                k = 'function';
        module.exports[name] = function (arg, name) {
                array(arg, k, name);
        };
});
 
Object.keys(module.exports).forEach(function (k) {
        var _name = 'optional' + capitalize(k);
        var s = uncapitalize(k.replace('arrayOf', ''));
        if (s === 'bool')
                s = 'boolean';
        if (s === 'func')
                s = 'function';
 
        if (k.indexOf('arrayOf') !== -1) {
          module.exports[_name] = function (arg, name) {
                  if (!NDEBUG && arg !== undefined) {
                          array(arg, s, name);
                  }
          };
        } else {
          module.exports[_name] = function (arg, name) {
                  if (!NDEBUG && arg !== undefined) {
                          _assert(arg, s, name);
                  }
          };
        }
});
 
 
// Reexport built-in assertions
Object.keys(assert).forEach(function (k) {
        if (k === 'AssertionError') {
                module.exports[k] = assert[k];
                return;
        }
 
        module.exports[k] = function () {
                if (!NDEBUG) {
                        assert[k].apply(assert[k], arguments);
                }
        };
});
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/

Statements: 12.75% (138 / 1082)      Branches: 0% (0 / 580)      Functions: 0% (0 / 83)      Lines: 12.77% (138 / 1081)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/
File Statements Branches Functions Lines
ctf.js 8.89% (12 / 135) 0% (0 / 92) 0% (0 / 6) 8.89% (12 / 135)
ctio.js 9.12% (52 / 570) 0% (0 / 329) 0% (0 / 31) 9.12% (52 / 570)
ctype.js 19.63% (74 / 377) 0% (0 / 159) 0% (0 / 46) 19.68% (74 / 376)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ctf.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ctf.js

Statements: 8.89% (12 / 135)      Branches: 0% (0 / 92)      Functions: 0% (0 / 6)      Lines: 8.89% (12 / 135)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247                    1 1   1 1 1     1                                                                                                             1                                                 1                                               1                                                                                             1                                                                                     1                                                               1    
/*
 * ctf.js
 *
 * Understand and parse all of the different JSON formats of CTF data and
 * translate that into a series of node-ctype friendly pieces. The reason for
 * the abstraction is to handle different changes in the file format.
 *
 * We have to be careful here that we don't end up using a name that is already
 * a built in type.
 */
var mod_assert = require('assert');
var ASSERT = mod_assert.ok;
 
var ctf_versions = [ '1.0' ];
var ctf_entries = [ 'integer', 'float', 'typedef', 'struct' ];
var ctf_deftypes = [ 'int8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int32_t',
    'uint32_t', 'float', 'double' ];
 
function ctfParseInteger(entry, ctype)
{
	var name, sign, len, type;
 
	name = entry['name'];
	if (!('signed' in entry['integer']))
		throw (new Error('Malformed CTF JSON: integer missing ' +
		    'signed value'));
 
 
	if (!('length' in entry['integer']))
		throw (new Error('Malformed CTF JSON: integer missing ' +
		    'length value'));
 
	sign = entry['integer']['signed'];
	len = entry['integer']['length'];
	type = null;
 
	if (sign && len == 1)
		type = 'int8_t';
	else if (len == 1)
		type = 'uint8_t';
	else if (sign && len == 2)
		type = 'int16_t';
	else if (len == 2)
		type = 'uint16_t';
	else if (sign && len == 4)
		type = 'int32_t';
	else if (len == 4)
		type = 'uint32_t';
	else if (sign && len == 8)
		type = 'int64_t';
	else if (len == 8)
		type = 'uint64_t';
 
	if (type === null)
		throw (new Error('Malformed CTF JSON: integer has ' +
		    'unsupported length and sign - ' + len + '/' + sign));
 
	/*
	 * This means that this is the same as one of our built in types. If
	 * that's the case defining it would be an error. So instead of trying
	 * to typedef it, we'll return here.
	 */
	if (name == type)
		return;
 
	if (name == 'char') {
		ASSERT(type == 'int8_t');
		return;
	}
 
	ctype.typedef(name, type);
}
 
function ctfParseFloat(entry, ctype)
{
	var name, len;
 
	name = entry['name'];
	if (!('length' in entry['float']))
		throw (new Error('Malformed CTF JSON: float missing ' +
		    'length value'));
 
	len = entry['float']['length'];
	if (len != 4 && len != 8)
		throw (new Error('Malformed CTF JSON: float has invalid ' +
		    'length value'));
 
	if (len == 4) {
		if (name == 'float')
			return;
		ctype.typedef(name, 'float');
	} else if (len == 8) {
		if (name == 'double')
			return;
		ctype.typedef(name, 'double');
	}
}
 
function ctfParseTypedef(entry, ctype)
{
	var name, type, ii;
 
	name = entry['name'];
	if (typeof (entry['typedef']) != 'string')
		throw (new Error('Malformed CTF JSON: typedef value in not ' +
		    'a string'));
 
	type = entry['typedef'];
 
	/*
	 * We need to ensure that we're not looking at type that's one of our
	 * built in types. Traditionally in C a uint32_t would be a typedef to
	 * some kind of integer. However, those size types are built ins.
	 */
	for (ii = 0; ii < ctf_deftypes.length; ii++) {
		if (name == ctf_deftypes[ii])
			return;
	}
 
	ctype.typedef(name, type);
}
 
function ctfParseStruct(entry, ctype)
{
	var name, type, ii, val, index, member, push;
 
	member = [];
	if (!Array.isArray(entry['struct']))
		throw (new Error('Malformed CTF JSON: struct value is not ' +
		    'an array'));
 
	for (ii = 0; ii < entry['struct'].length; ii++) {
		val = entry['struct'][ii];
		if (!('name' in val))
			throw (new Error('Malformed CTF JSON: struct member ' +
			    'missing name'));
 
		if (!('type' in val))
			throw (new Error('Malformed CTF JSON: struct member ' +
			    'missing type'));
 
		if (typeof (val['name']) != 'string')
			throw (new Error('Malformed CTF JSON: struct member ' +
			    'name isn\'t a string'));
 
		if (typeof (val['type']) != 'string')
			throw (new Error('Malformed CTF JSON: struct member ' +
			    'type isn\'t a string'));
 
		/*
		 * CTF version 2 specifies array names as <type> [<num>] where
		 * as node-ctype does this as <type>[<num>].
		 */
		name = val['name'];
		type = val['type'];
		index = type.indexOf(' [');
		if (index != -1) {
			type = type.substring(0, index) +
			    type.substring(index + 1, type.length);
		}
		push = {};
		push[name] = { 'type': type };
		member.push(push);
	}
 
	name = entry['name'];
	ctype.typedef(name, member);
}
 
function ctfParseEntry(entry, ctype)
{
	var ii, found;
 
	if (!('name' in entry))
		throw (new Error('Malformed CTF JSON: entry missing "name" ' +
		    'section'));
 
	for (ii = 0; ii < ctf_entries.length; ii++) {
		if (ctf_entries[ii] in entry)
			found++;
	}
 
	if (found === 0)
		throw (new Error('Malformed CTF JSON: found no entries'));
 
	if (found >= 2)
		throw (new Error('Malformed CTF JSON: found more than one ' +
		    'entry'));
 
	if ('integer' in entry) {
		ctfParseInteger(entry, ctype);
		return;
	}
 
	if ('float' in entry) {
		ctfParseFloat(entry, ctype);
		return;
	}
 
	if ('typedef' in entry) {
		ctfParseTypedef(entry, ctype);
		return;
	}
 
	if ('struct' in entry) {
		ctfParseStruct(entry, ctype);
		return;
	}
 
	ASSERT(false, 'shouldn\'t reach here');
}
 
function ctfParseJson(json, ctype)
{
	var version, ii;
 
	ASSERT(json);
	ASSERT(ctype);
	if (!('metadata' in json))
		throw (new Error('Invalid CTF JSON: missing metadata section'));
 
	if (!('ctf2json_version' in json['metadata']))
		throw (new Error('Invalid CTF JSON: missing ctf2json_version'));
 
	version = json['metadata']['ctf2json_version'];
	for (ii = 0; ii < ctf_versions.length; ii++) {
		if (ctf_versions[ii] == version)
			break;
	}
 
	if (ii == ctf_versions.length)
		throw (new Error('Unsuported ctf2json_version: ' + version));
 
	if (!('data' in json))
		throw (new Error('Invalid CTF JSON: missing data section'));
 
	if (!Array.isArray(json['data']))
		throw (new Error('Malformed CTF JSON: data section is not ' +
		    'an array'));
 
	for (ii = 0; ii < json['data'].length; ii++)
		ctfParseEntry(json['data'][ii], ctype);
}
 
exports.ctfParseJson = ctfParseJson;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ctio.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ctio.js

Statements: 9.12% (52 / 570)      Branches: 0% (0 / 329)      Functions: 0% (0 / 31)      Lines: 9.12% (52 / 570)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487                                                                                    1         1                                       1                               1                                                             1                                     1                                                                 1                             1                                                                                                                                                 1                                                     1                                                               1                                                       1                                                                                                                                                                                                 1                                                                                                                                                                                                             1                                                                                                                                                                                                                                                                           1                                           1                                                     1                     1                                                                   1                               1                                                       1                     1                                                                                                                                                       1                                       1                                                         1                                                             1                                                               1                                                                                                                                                                                                                                                                                                                             1               1               1         1                                                                                                                                                                                                                                                                                     1                                                                                                                                                                                                                                                                       1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1   1 1 1 1    
/*
 * rm - Feb 2011
 * ctio.js:
 *
 * A simple way to read and write simple ctypes. Of course, as you'll find the
 * code isn't as simple as it might appear. The following types are currently
 * supported in big and little endian formats:
 *
 * 	uint8_t			int8_t
 * 	uint16_t		int16_t
 * 	uint32_t		int32_t
 *	float (single precision IEEE 754)
 *	double (double precision IEEE 754)
 *
 * This is designed to work in Node and v8. It may in fact work in other
 * Javascript interpreters (that'd be pretty neat), but it hasn't been tested.
 * If you find that it does in fact work, that's pretty cool. Try and pass word
 * back to the original author.
 *
 * Note to the reader: If you're tabstop isn't set to 8, parts of this may look
 * weird.
 */
 
/*
 * Numbers in Javascript have a secret: all numbers must be represented with an
 * IEEE-754 double. The double has a mantissa with a length of 52 bits with an
 * implicit one. Thus the range of integers that can be represented is limited
 * to the size of the mantissa, this makes reading and writing 64-bit integers
 * difficult, but far from impossible.
 *
 * Another side effect of this representation is what happens when you use the
 * bitwise operators, i.e. shift left, shift right, and, or, etc. In Javascript,
 * each operand and the result is cast to a signed 32-bit number. However, in
 * the case of >>> the values are cast to an unsigned number.
 */
 
/*
 * A reminder on endian related issues:
 *
 * Big Endian: MSB -> First byte
 * Little Endian: MSB->Last byte
 */
var mod_assert = require('assert');
 
/*
 * An 8 bit unsigned integer involves doing no significant work.
 */
function ruint8(buffer, endian, offset)
{
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	return (buffer[offset]);
}
 
/*
 * For 16 bit unsigned numbers we can do all the casting that we want to do.
 */
function rgint16(buffer, endian, offset)
{
	var val = 0;
 
	if (endian == 'big') {
		val = buffer[offset] << 8;
		val |=  buffer[offset+1];
	} else {
		val = buffer[offset];
		val |= buffer[offset+1] << 8;
	}
 
	return (val);
 
}
 
function ruint16(buffer, endian, offset)
{
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 1 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	return (rgint16(buffer, endian, offset));
}
 
/*
 * Because most bitshifting is done using signed numbers, if we would go into
 * the realm where we use that 32nd bit, we'll end up going into the negative
 * range. i.e.:
 * > 200 << 24
 * -939524096
 *
 * Not the value you'd expect. To work around this, we end up having to do some
 * abuse of the JavaScript standard. in this case, we know that a >>> shift is
 * defined to cast our value to an *unsigned* 32-bit number. Because of that, we
 * use that instead to save us some additional math, though it does feel a
 * little weird and it isn't obvious as to why you woul dwant to do this at
 * first.
 */
function rgint32(buffer, endian, offset)
{
	var val = 0;
 
	if (endian == 'big') {
		val = buffer[offset+1] << 16;
		val |= buffer[offset+2] << 8;
		val |= buffer[offset+3];
		val = val + (buffer[offset] << 24 >>> 0);
	} else {
		val = buffer[offset+2] << 16;
		val |= buffer[offset+1] << 8;
		val |= buffer[offset];
		val = val + (buffer[offset + 3] << 24 >>> 0);
	}
 
	return (val);
}
 
function ruint32(buffer, endian, offset)
{
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	return (rgint32(buffer, endian, offset));
}
 
/*
 * Reads a 64-bit unsigned number. The astue observer will note that this
 * doesn't quite work. Javascript has chosen to only have numbers that can be
 * represented by a double. A double only has 52 bits of mantissa with an
 * implicit 1, thus we have up to 53 bits to represent an integer. However, 2^53
 * doesn't quite give us what we want. Isn't 53 bits enough for anyone? What
 * could you have possibly wanted to represent that was larger than that? Oh,
 * maybe a size? You mean we bypassed the 4 GB limit on file sizes, when did
 * that happen?
 *
 * To get around this egregious language issue, we're going to instead construct
 * an array of two 32 bit unsigned integers. Where arr[0] << 32 + arr[1] would
 * give the actual number. However, note that the above code probably won't
 * produce the desired results because of the way Javascript numbers are
 * doubles.
 */
function rgint64(buffer, endian, offset)
{
	var val = new Array(2);
 
	if (endian == 'big') {
		val[0] = ruint32(buffer, endian, offset);
		val[1] = ruint32(buffer, endian, offset+4);
	} else {
		val[0] = ruint32(buffer, endian, offset+4);
		val[1] = ruint32(buffer, endian, offset);
	}
 
	return (val);
}
 
function ruint64(buffer, endian, offset)
{
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 7 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	return (rgint64(buffer, endian, offset));
}
 
 
/*
 * Signed integer types, yay team! A reminder on how two's complement actually
 * works. The first bit is the signed bit, i.e. tells us whether or not the
 * number should be positive or negative. If the two's complement value is
 * positive, then we're done, as it's equivalent to the unsigned representation.
 *
 * Now if the number is positive, you're pretty much done, you can just leverage
 * the unsigned translations and return those. Unfortunately, negative numbers
 * aren't quite that straightforward.
 *
 * At first glance, one might be inclined to use the traditional formula to
 * translate binary numbers between the positive and negative values in two's
 * complement. (Though it doesn't quite work for the most negative value)
 * Mainly:
 *  - invert all the bits
 *  - add one to the result
 *
 * Of course, this doesn't quite work in Javascript. Take for example the value
 * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
 * course, Javascript will do the following:
 *
 * > ~0xff80
 * -65409
 *
 * Whoh there, Javascript, that's not quite right. But wait, according to
 * Javascript that's perfectly correct. When Javascript ends up seeing the
 * constant 0xff80, it has no notion that it is actually a signed number. It
 * assumes that we've input the unsigned value 0xff80. Thus, when it does the
 * binary negation, it casts it into a signed value, (positive 0xff80). Then
 * when you perform binary negation on that, it turns it into a negative number.
 *
 * Instead, we're going to have to use the following general formula, that works
 * in a rather Javascript friendly way. I'm glad we don't support this kind of
 * weird numbering scheme in the kernel.
 *
 * (BIT-MAX - (unsigned)val + 1) * -1
 *
 * The astute observer, may think that this doesn't make sense for 8-bit numbers
 * (really it isn't necessary for them). However, when you get 16-bit numbers,
 * you do. Let's go back to our prior example and see how this will look:
 *
 * (0xffff - 0xff80 + 1) * -1
 * (0x007f + 1) * -1
 * (0x0080) * -1
 *
 * Doing it this way ends up allowing us to treat it appropriately in
 * Javascript. Sigh, that's really quite ugly for what should just be a few bit
 * shifts, ~ and &.
 */
 
/*
 * Endianness doesn't matter for 8-bit signed values. We could in fact optimize
 * this case because the more traditional methods work, but for consistency,
 * we'll keep doing this the same way.
 */
function rsint8(buffer, endian, offset)
{
	var neg;
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	neg = buffer[offset] & 0x80;
	if (!neg)
		return (buffer[offset]);
 
	return ((0xff - buffer[offset] + 1) * -1);
}
 
/*
 * The 16-bit version requires a bit more effort. In this case, we can leverage
 * our unsigned code to generate the value we want to return.
 */
function rsint16(buffer, endian, offset)
{
	var neg, val;
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 1 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = rgint16(buffer, endian, offset);
	neg = val & 0x8000;
	if (!neg)
		return (val);
 
	return ((0xffff - val + 1) * -1);
}
 
/*
 * We really shouldn't leverage our 32-bit code here and instead utilize the
 * fact that we know that since these are signed numbers, we can do all the
 * shifting and binary anding to generate the 32-bit number. But, for
 * consistency we'll do the same. If we want to do otherwise, we should instead
 * make the 32 bit unsigned code do the optimization. But as long as there
 * aren't floats secretly under the hood for that, we /should/ be okay.
 */
function rsint32(buffer, endian, offset)
{
	var neg, val;
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = rgint32(buffer, endian, offset);
	neg = val & 0x80000000;
	if (!neg)
		return (val);
 
	return ((0xffffffff - val + 1) * -1);
}
 
/*
 * The signed version of this code suffers from all of the same problems of the
 * other 64 bit version.
 */
function rsint64(buffer, endian, offset)
{
	var neg, val;
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = rgint64(buffer, endian, offset);
	neg = val[0] & 0x80000000;
 
	if (!neg)
		return (val);
 
	val[0] = (0xffffffff - val[0]) * -1;
	val[1] = (0xffffffff - val[1] + 1) * -1;
 
	/*
	 * If we had the key 0x8000000000000000, that would leave the lower 32
	 * bits as 0xffffffff, however, since we're goint to add one, that would
	 * actually leave the lower 32-bits as 0x100000000, which would break
	 * our ability to write back a value that we received. To work around
	 * this, if we actually get that value, we're going to bump the upper
	 * portion by 1 and set this to zero.
	 */
	mod_assert.ok(val[1] <= 0x100000000);
	if (val[1] == -0x100000000) {
		val[1] = 0;
		val[0]--;
	}
 
	return (val);
}
 
/*
 * We now move onto IEEE 754: The traditional form for floating point numbers
 * and what is secretly hiding at the heart of everything in this. I really hope
 * that someone is actually using this, as otherwise, this effort is probably
 * going to be more wasted.
 *
 * One might be tempted to use parseFloat here, but that wouldn't work at all
 * for several reasons. Mostly due to the way floats actually work, and
 * parseFloat only actually works in base 10. I don't see base 10 anywhere near
 * this file.
 *
 * In this case we'll implement the single and double precision versions. The
 * quadruple precision, while probably useful, wouldn't really be accepted by
 * Javascript, so let's not even waste our time.
 *
 * So let's review how this format looks like. A single precision value is 32
 * bits and has three parts:
 *   -  Sign bit
 *   -  Exponent (Using bias notation)
 *   -  Mantissa
 *
 * |s|eeeeeeee|mmmmmmmmmmmmmmmmmmmmmmmmm|
 * 31| 30-23  |  22    	-       0       |
 *
 * The exponent is stored in a biased input. The bias in this case 127.
 * Therefore, our exponent is equal to the 8-bit value - 127.
 *
 * By default, a number is normalized in IEEE, that means that the mantissa has
 * an implicit one that we don't see. So really the value stored is 1.m.
 * However, if the exponent is all zeros, then instead we have to shift
 * everything to the right one and there is no more implicit one.
 *
 * Special values:
 *  - Positive Infinity:
 *	Sign:		0
 *	Exponent: 	All 1s
 *	Mantissa:	0
 *  - Negative Infinity:
 *	Sign:		1
 *	Exponent: 	All 1s
 *	Mantissa:	0
 *  - NaN:
 *	Sign:		*
 *	Exponent: 	All 1s
 *	Mantissa:	non-zero
 *  - Zero:
 *	Sign:		*
 *	Exponent:	All 0s
 *	Mantissa:	0
 *
 * In the case of zero, the sign bit determines whether we get a positive or
 * negative zero. However, since Javascript cannot determine the difference
 * between the two: i.e. -0 == 0, we just always return 0.
 *
 */
function rfloat(buffer, endian, offset)
{
	var bytes = [];
	var sign, exponent, mantissa, val;
	var bias = 127;
	var maxexp = 0xff;
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	/* Normalize the bytes to be in endian order */
	if (endian == 'big') {
		bytes[0] = buffer[offset];
		bytes[1] = buffer[offset+1];
		bytes[2] = buffer[offset+2];
		bytes[3] = buffer[offset+3];
	} else {
		bytes[3] = buffer[offset];
		bytes[2] = buffer[offset+1];
		bytes[1] = buffer[offset+2];
		bytes[0] = buffer[offset+3];
	}
 
	sign = bytes[0] & 0x80;
	exponent = (bytes[0] & 0x7f) << 1;
	exponent |= (bytes[1] & 0x80) >>> 7;
	mantissa = (bytes[1] & 0x7f) << 16;
	mantissa |= bytes[2] << 8;
	mantissa |= bytes[3];
 
	/* Check for special cases before we do general parsing */
	if (!sign && exponent == maxexp && mantissa === 0)
		return (Number.POSITIVE_INFINITY);
 
	if (sign && exponent == maxexp && mantissa === 0)
		return (Number.NEGATIVE_INFINITY);
 
	if (exponent == maxexp && mantissa !== 0)
		return (Number.NaN);
 
	/*
	 * Javascript really doesn't have support for positive or negative zero.
	 * So we're not going to try and give it to you. That would be just
	 * plain weird. Besides -0 == 0.
	 */
	if (exponent === 0 && mantissa === 0)
		return (0);
 
	/*
	 * Now we can deal with the bias and the determine whether the mantissa
	 * has the implicit one or not.
	 */
	exponent -= bias;
	if (exponent == -bias) {
		exponent++;
		val = 0;
	} else {
		val = 1;
	}
 
	val = (val + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent);
 
	if (sign)
		val *= -1;
 
	return (val);
}
 
/*
 * Doubles in IEEE 754 are like their brothers except for a few changes and
 * increases in size:
 *   - The exponent is now 11 bits
 *   - The mantissa is now 52 bits
 *   - The bias is now 1023
 *
 * |s|eeeeeeeeeee|mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm|
 * 63| 62 - 52   | 	51		-			0     |
 * 63| 62 - 52   |      51              -                       0     |
 *
 * While the size has increased a fair amount, we're going to end up keeping the
 * same general formula for calculating the final value. As a reminder, this
 * formula is:
 *
 * (-1)^s * (n + m) * 2^(e-b)
 *
 * Where:
 *	s	is the sign bit
 *	n	is (exponent > 0) ? 1 : 0 -- Determines whether we're normalized
 *					     or not
 *	m	is the mantissa
 *	e	is the exponent specified
 *	b	is the bias for the exponent
 *
 */
function rdouble(buffer, endian, offset)
{
	var bytes = [];
	var sign, exponent, mantissa, val, lowmant;
	var bias = 1023;
	var maxexp = 0x7ff;
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 7 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	/* Normalize the bytes to be in endian order */
	if (endian == 'big') {
		bytes[0] = buffer[offset];
		bytes[1] = buffer[offset+1];
		bytes[2] = buffer[offset+2];
		bytes[3] = buffer[offset+3];
		bytes[4] = buffer[offset+4];
		bytes[5] = buffer[offset+5];
		bytes[6] = buffer[offset+6];
		bytes[7] = buffer[offset+7];
	} else {
		bytes[7] = buffer[offset];
		bytes[6] = buffer[offset+1];
		bytes[5] = buffer[offset+2];
		bytes[4] = buffer[offset+3];
		bytes[3] = buffer[offset+4];
		bytes[2] = buffer[offset+5];
		bytes[1] = buffer[offset+6];
		bytes[0] = buffer[offset+7];
	}
 
	/*
	 * We can construct the exponent and mantissa the same way as we did in
	 * the case of a float, just increase the range of the exponent.
	 */
	sign = bytes[0] & 0x80;
	exponent = (bytes[0] & 0x7f) << 4;
	exponent |= (bytes[1] & 0xf0) >>> 4;
 
	/*
	 * This is going to be ugly but then again, we're dealing with IEEE 754.
	 * This could probably be done as a node add on in a few lines of C++,
	 * but oh we'll, we've made it this far so let's be native the rest of
	 * the way...
	 *
	 * What we're going to do is break the mantissa into two parts, the
	 * lower 24 bits and the upper 28 bits. We'll multiply the upper 28 bits
	 * by the appropriate power and then add in the lower 24-bits. Not
	 * really that great. It's pretty much a giant kludge to deal with
	 * Javascript eccentricities around numbers.
	 */
	lowmant = bytes[7];
	lowmant |= bytes[6] << 8;
	lowmant |= bytes[5] << 16;
	mantissa = bytes[4];
	mantissa |= bytes[3] << 8;
	mantissa |= bytes[2] << 16;
	mantissa |= (bytes[1] & 0x0f) << 24;
	mantissa *= Math.pow(2, 24); /* Equivalent to << 24, but JS compat */
	mantissa += lowmant;
 
	/* Check for special cases before we do general parsing */
	if (!sign && exponent == maxexp && mantissa === 0)
		return (Number.POSITIVE_INFINITY);
 
	if (sign && exponent == maxexp && mantissa === 0)
		return (Number.NEGATIVE_INFINITY);
 
	if (exponent == maxexp && mantissa !== 0)
		return (Number.NaN);
 
	/*
	 * Javascript really doesn't have support for positive or negative zero.
	 * So we're not going to try and give it to you. That would be just
	 * plain weird. Besides -0 == 0.
	 */
	if (exponent === 0 && mantissa === 0)
		return (0);
 
	/*
	 * Now we can deal with the bias and the determine whether the mantissa
	 * has the implicit one or not.
	 */
	exponent -= bias;
	if (exponent == -bias) {
		exponent++;
		val = 0;
	} else {
		val = 1;
	}
 
	val = (val + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent);
 
	if (sign)
		val *= -1;
 
	return (val);
}
 
/*
 * Now that we have gone through the pain of reading the individual types, we're
 * probably going to want some way to write these back. None of this is going to
 * be good. But since we have Javascript numbers this should certainly be more
 * interesting. Though we can constrain this end a little bit more in what is
 * valid. For now, let's go back to our friends the unsigned value.
 */
 
/*
 * Unsigned numbers seem deceptively easy. Here are the general steps and rules
 * that we are going to take:
 *   -  If the number is negative, throw an Error
 *   -  Truncate any floating point portion
 *   -  Take the modulus of the number in our base
 *   -  Write it out to the buffer in the endian format requested at the offset
 */
 
/*
 * We have to make sure that the value is a valid integer. This means that it is
 * non-negative. It has no fractional component and that it does not exceed the
 * maximum allowed value.
 *
 *	value		The number to check for validity
 *
 *	max		The maximum value
 */
function prepuint(value, max)
{
	if (typeof (value) != 'number')
		throw (new (Error('cannot write a non-number as a number')));
 
	if (value < 0)
		throw (new Error('specified a negative value for writing an ' +
		    'unsigned value'));
 
	if (value > max)
		throw (new Error('value is larger than maximum value for ' +
		    'type'));
 
	if (Math.floor(value) !== value)
		throw (new Error('value has a fractional component'));
 
	return (value);
}
 
/*
 * 8-bit version, classy. We can ignore endianness which is good.
 */
function wuint8(value, endian, buffer, offset)
{
	var val;
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = prepuint(value, 0xff);
	buffer[offset] = val;
}
 
/*
 * Pretty much the same as the 8-bit version, just this time we need to worry
 * about endian related issues.
 */
function wgint16(val, endian, buffer, offset)
{
	if (endian == 'big') {
		buffer[offset] = (val & 0xff00) >>> 8;
		buffer[offset+1] = val & 0x00ff;
	} else {
		buffer[offset+1] = (val & 0xff00) >>> 8;
		buffer[offset] = val & 0x00ff;
	}
}
 
function wuint16(value, endian, buffer, offset)
{
	var val;
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 1 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = prepuint(value, 0xffff);
	wgint16(val, endian, buffer, offset);
}
 
/*
 * The 32-bit version is going to have to be a little different unfortunately.
 * We can't quite bitshift to get the largest byte, because that would end up
 * getting us caught by the signed values.
 *
 * And yes, we do want to subtract out the lower part by default. This means
 * that when we do the division, it will be treated as a bit shift and we won't
 * end up generating a floating point value. If we did generate a floating point
 * value we'd have to truncate it intelligently, this saves us that problem and
 * may even be somewhat faster under the hood.
 */
function wgint32(val, endian, buffer, offset)
{
	if (endian == 'big') {
		buffer[offset] = (val - (val & 0x00ffffff)) / Math.pow(2, 24);
		buffer[offset+1] = (val >>> 16) & 0xff;
		buffer[offset+2] = (val >>> 8) & 0xff;
		buffer[offset+3] = val & 0xff;
	} else {
		buffer[offset+3] = (val - (val & 0x00ffffff)) /
		    Math.pow(2, 24);
		buffer[offset+2] = (val >>> 16) & 0xff;
		buffer[offset+1] = (val >>> 8) & 0xff;
		buffer[offset] = val & 0xff;
	}
}
 
function wuint32(value, endian, buffer, offset)
{
	var val;
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = prepuint(value, 0xffffffff);
	wgint32(val, endian, buffer, offset);
}
 
/*
 * Unlike the other versions, we expect the value to be in the form of two
 * arrays where value[0] << 32 + value[1] would result in the value that we
 * want.
 */
function wgint64(value, endian, buffer, offset)
{
	if (endian == 'big') {
		wgint32(value[0], endian, buffer, offset);
		wgint32(value[1], endian, buffer, offset+4);
	} else {
		wgint32(value[0], endian, buffer, offset+4);
		wgint32(value[1], endian, buffer, offset);
	}
}
 
function wuint64(value, endian, buffer, offset)
{
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (!(value instanceof Array))
		throw (new Error('value must be an array'));
 
	if (value.length != 2)
		throw (new Error('value must be an array of length 2'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 7 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	prepuint(value[0], 0xffffffff);
	prepuint(value[1], 0xffffffff);
	wgint64(value, endian, buffer, offset);
}
 
/*
 * We now move onto our friends in the signed number category. Unlike unsigned
 * numbers, we're going to have to worry a bit more about how we put values into
 * arrays. Since we are only worrying about signed 32-bit values, we're in
 * slightly better shape. Unfortunately, we really can't do our favorite binary
 * & in this system. It really seems to do the wrong thing. For example:
 *
 * > -32 & 0xff
 * 224
 *
 * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
 * this aren't treated as a signed number. Ultimately a bad thing.
 *
 * What we're going to want to do is basically create the unsigned equivalent of
 * our representation and pass that off to the wuint* functions. To do that
 * we're going to do the following:
 *
 *  - if the value is positive
 *	we can pass it directly off to the equivalent wuint
 *  - if the value is negative
 *	we do the following computation:
 *	mb + val + 1, where
 *	mb	is the maximum unsigned value in that byte size
 *	val	is the Javascript negative integer
 *
 *
 * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
 * you do out the computations:
 *
 * 0xffff - 128 + 1
 * 0xffff - 127
 * 0xff80
 *
 * You can then encode this value as the signed version. This is really rather
 * hacky, but it should work and get the job done which is our goal here.
 *
 * Thus the overall flow is:
 *   -  Truncate the floating point part of the number
 *   -  We don't have to take the modulus, because the unsigned versions will
 *   	take care of that for us. And we don't have to worry about that
 *   	potentially causing bad things to happen because of sign extension
 *   -  Pass it off to the appropriate unsigned version, potentially modifying
 *	the negative portions as necessary.
 */
 
/*
 * A series of checks to make sure we actually have a signed 32-bit number
 */
function prepsint(value, max, min)
{
	if (typeof (value) != 'number')
		throw (new (Error('cannot write a non-number as a number')));
 
	if (value > max)
		throw (new Error('value larger than maximum allowed value'));
 
	if (value < min)
		throw (new Error('value smaller than minimum allowed value'));
 
	if (Math.floor(value) !== value)
		throw (new Error('value has a fractional component'));
 
	return (value);
}
 
/*
 * The 8-bit version of the signed value. Overall, fairly straightforward.
 */
function wsint8(value, endian, buffer, offset)
{
	var val;
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = prepsint(value, 0x7f, -0x80);
	if (val >= 0)
		wuint8(val, endian, buffer, offset);
	else
		wuint8(0xff + val + 1, endian, buffer, offset);
}
 
/*
 * The 16-bit version of the signed value. Also, fairly straightforward.
 */
function wsint16(value, endian, buffer, offset)
{
	var val;
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 1 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = prepsint(value, 0x7fff, -0x8000);
	if (val >= 0)
		wgint16(val, endian, buffer, offset);
	else
		wgint16(0xffff + val + 1, endian, buffer, offset);
 
}
 
/*
 * We can do this relatively easily by leveraging the code used for 32-bit
 * unsigned code.
 */
function wsint32(value, endian, buffer, offset)
{
	var val;
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	val = prepsint(value, 0x7fffffff, -0x80000000);
	if (val >= 0)
		wgint32(val, endian, buffer, offset);
	else
		wgint32(0xffffffff + val + 1, endian, buffer, offset);
}
 
/*
 * The signed 64 bit integer should by in the same format as when received.
 * Mainly it should ensure that the value is an array of two integers where
 * value[0] << 32 + value[1] is the desired number. Furthermore, the two values
 * need to be equal.
 */
function wsint64(value, endian, buffer, offset)
{
	var vzpos, vopos;
	var vals = new Array(2);
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (!(value instanceof Array))
		throw (new Error('value must be an array'));
 
	if (value.length != 2)
		throw (new Error('value must be an array of length 2'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
	if (offset + 7 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	/*
	 * We need to make sure that we have the same sign on both values. The
	 * hokiest way to to do this is to multiply the number by +inf. If we do
	 * this, we'll get either +/-inf depending on the sign of the value.
	 * Once we have this, we can compare it to +inf to see if the number is
	 * positive or not.
	 */
	vzpos = (value[0] * Number.POSITIVE_INFINITY) ==
	    Number.POSITIVE_INFINITY;
	vopos = (value[1] * Number.POSITIVE_INFINITY) ==
	    Number.POSITIVE_INFINITY;
 
	/*
	 * If either of these is zero, then we don't actually need this check.
	 */
	if (value[0] != 0 && value[1] != 0 && vzpos != vopos)
		throw (new Error('Both entries in the array must have ' +
		    'the same sign'));
 
	/*
	 * Doing verification for a signed 64-bit integer is actually a big
	 * trickier than it appears. We can't quite use our standard techniques
	 * because we need to compare both sets of values. The first value is
	 * pretty straightforward. If the first value is beond the extremes than
	 * we error out. However, the valid range of the second value varies
	 * based on the first one. If the first value is negative, and *not* the
	 * largest negative value, than it can be any integer within the range [
	 * 0, 0xffffffff ]. If it is the largest negative number, it must be
	 * zero.
	 *
	 * If the first number is positive, than it doesn't matter what the
	 * value is. We just simply have to make sure we have a valid positive
	 * integer.
	 */
	if (vzpos) {
		prepuint(value[0], 0x7fffffff);
		prepuint(value[1], 0xffffffff);
	} else {
		prepsint(value[0], 0, -0x80000000);
		prepsint(value[1], 0, -0xffffffff);
		if (value[0] == -0x80000000 && value[1] != 0)
			throw (new Error('value smaller than minimum ' +
			    'allowed value'));
	}
 
	/* Fix negative numbers */
	if (value[0] < 0 || value[1] < 0) {
		vals[0] = 0xffffffff - Math.abs(value[0]);
		vals[1] = 0x100000000 - Math.abs(value[1]);
		if (vals[1] == 0x100000000) {
			vals[1] = 0;
			vals[0]++;
		}
	} else {
		vals[0] = value[0];
		vals[1] = value[1];
	}
	wgint64(vals, endian, buffer, offset);
}
 
/*
 * Now we are moving onto the weirder of these, the float and double. For this
 * we're going to just have to do something that's pretty weird. First off, we
 * have no way to get at the underlying float representation, at least not
 * easily. But that doesn't mean we can't figure it out, we just have to use our
 * heads.
 *
 * One might propose to use Number.toString(2). Of course, this is not really
 * that good, because the ECMAScript 262 v3 Standard says the following Section
 * 15.7.4.2-Number.prototype.toString (radix):
 *
 * If radix is an integer from 2 to 36, but not 10, the result is a string, the
 * choice of which is implementation-dependent.
 *
 * Well that doesn't really help us one bit now does it? We could use the
 * standard base 10 version of the string, but that's just going to create more
 * errors as we end up trying to convert it back to a binary value. So, really
 * this just means we have to be non-lazy and parse the structure intelligently.
 *
 * First off, we can do the basic checks: NaN, positive and negative infinity.
 *
 * Now that those are done we can work backwards to generate the mantissa and
 * exponent.
 *
 * The first thing we need to do is determine the sign bit, easy to do, check
 * whether the value is less than 0. And convert the number to its absolute
 * value representation. Next, we need to determine if the value is less than
 * one or greater than or equal to one and from there determine what power was
 * used to get there. What follows is now specific to floats, though the general
 * ideas behind this will hold for doubles as well, but the exact numbers
 * involved will change.
 *
 * Once we have that power we can determine the exponent and the mantissa. Call
 * the value that has the number of bits to reach the power ebits. In the
 * general case they have the following values:
 *
 *	exponent	127 + ebits
 *	mantissa	value * 2^(23 - ebits) & 0x7fffff
 *
 * In the case where the value of ebits is <= -127 we are now in the case where
 * we no longer have normalized numbers. In this case the values take on the
 * following values:
 *
 * 	exponent	0
 *	mantissa	value * 2^149 & 0x7fffff
 *
 * Once we have the values for the sign, mantissa, and exponent. We reconstruct
 * the four bytes as follows:
 *
 *	byte0		sign bit and seven most significant bits from the exp
 *			sign << 7 | (exponent & 0xfe) >>> 1
 *
 *	byte1		lsb from the exponent and 7 top bits from the mantissa
 *			(exponent & 0x01) << 7 | (mantissa & 0x7f0000) >>> 16
 *
 *	byte2		bits 8-15 (zero indexing) from mantissa
 *			mantissa & 0xff00 >> 8
 *
 *	byte3		bits 0-7 from mantissa
 *			mantissa & 0xff
 *
 * Once we have this we have to assign them into the buffer in proper endian
 * order.
 */
 
/*
 * Compute the log base 2 of the value. Now, someone who remembers basic
 * properties of logarithms will point out that we could use the change of base
 * formula for logs, and in fact that would be astute, because that's what we'll
 * do for now. It feels cleaner, albeit it may be less efficient than just
 * iterating and dividing by 2. We may want to come back and revisit that some
 * day.
 */
function log2(value)
{
	return (Math.log(value) / Math.log(2));
}
 
/*
 * Helper to determine the exponent of the number we're looking at.
 */
function intexp(value)
{
	return (Math.floor(log2(value)));
}
 
/*
 * Helper to determine the exponent of the fractional part of the value.
 */
function fracexp(value)
{
	return (Math.floor(log2(value)));
}
 
function wfloat(value, endian, buffer, offset)
{
	var sign, exponent, mantissa, ebits;
	var bytes = [];
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
 
	if (offset + 3 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	if (isNaN(value)) {
		sign = 0;
		exponent = 0xff;
		mantissa = 23;
	} else if (value == Number.POSITIVE_INFINITY) {
		sign = 0;
		exponent = 0xff;
		mantissa = 0;
	} else if (value == Number.NEGATIVE_INFINITY) {
		sign = 1;
		exponent = 0xff;
		mantissa = 0;
	} else {
		/* Well we have some work to do */
 
		/* Thankfully the sign bit is trivial */
		if (value < 0) {
			sign = 1;
			value = Math.abs(value);
		} else {
			sign = 0;
		}
 
		/* Use the correct function to determine number of bits */
		if (value < 1)
			ebits = fracexp(value);
		else
			ebits = intexp(value);
 
		/* Time to deal with the issues surrounding normalization */
		if (ebits <= -127) {
			exponent = 0;
			mantissa = (value * Math.pow(2, 149)) & 0x7fffff;
		} else {
			exponent = 127 + ebits;
			mantissa = value * Math.pow(2, 23 - ebits);
			mantissa &= 0x7fffff;
		}
	}
 
	bytes[0] = sign << 7 | (exponent & 0xfe) >>> 1;
	bytes[1] = (exponent & 0x01) << 7 | (mantissa & 0x7f0000) >>> 16;
	bytes[2] = (mantissa & 0x00ff00) >>> 8;
	bytes[3] = mantissa & 0x0000ff;
 
	if (endian == 'big') {
		buffer[offset] = bytes[0];
		buffer[offset+1] = bytes[1];
		buffer[offset+2] = bytes[2];
		buffer[offset+3] = bytes[3];
	} else {
		buffer[offset] = bytes[3];
		buffer[offset+1] = bytes[2];
		buffer[offset+2] = bytes[1];
		buffer[offset+3] = bytes[0];
	}
}
 
/*
 * Now we move onto doubles. Doubles are similar to floats in pretty much all
 * ways except that the processing isn't quite as straightforward because we
 * can't always use shifting, i.e. we have > 32 bit values.
 *
 * We're going to proceed in an identical fashion to floats and utilize the same
 * helper functions. All that really is changing are the specific values that we
 * use to do the calculations. Thus, to review we have to do the following.
 *
 * First get the sign bit and convert the value to its absolute value
 * representation. Next, we determine the number of bits that we used to get to
 * the value, branching whether the value is greater than or less than 1. Once
 * we have that value which we will again call ebits, we have to do the
 * following in the general case:
 *
 *	exponent	1023 + ebits
 *	mantissa	[value * 2^(52 - ebits)] % 2^52
 *
 * In the case where the value of ebits <= -1023 we no longer use normalized
 * numbers, thus like with floats we have to do slightly different processing:
 *
 *	exponent	0
 *	mantissa	[value * 2^1074] % 2^52
 *
 * Once we have determined the sign, exponent and mantissa we can construct the
 * bytes as follows:
 *
 *	byte0		sign bit and seven most significant bits form the exp
 *			sign << 7 | (exponent & 0x7f0) >>> 4
 *
 *	byte1		Remaining 4 bits from the exponent and the four most
 *			significant bits from the mantissa 48-51
 *			(exponent & 0x00f) << 4 | mantissa >>> 48
 *
 *	byte2		Bits 40-47 from the mantissa
 *			(mantissa >>> 40) & 0xff
 *
 *	byte3		Bits 32-39 from the mantissa
 *			(mantissa >>> 32) & 0xff
 *
 *	byte4		Bits 24-31 from the mantissa
 *			(mantissa >>> 24) & 0xff
 *
 *	byte5		Bits 16-23 from the Mantissa
 *			(mantissa >>> 16) & 0xff
 *
 *	byte6		Bits 8-15 from the mantissa
 *			(mantissa >>> 8) & 0xff
 *
 *	byte7		Bits 0-7 from the mantissa
 *			mantissa & 0xff
 *
 * Now we can't quite do the right shifting that we want in bytes 1 - 3, because
 * we'll have extended too far and we'll lose those values when we try and do
 * the shift. Instead we have to use an alternate approach. To try and stay out
 * of floating point, what we'll do is say that mantissa -= bytes[4-7] and then
 * divide by 2^32. Once we've done that we can use binary arithmetic. Oof,
 * that's ugly, but it seems to avoid using floating point (just based on how v8
 * seems to be optimizing for base 2 arithmetic).
 */
function wdouble(value, endian, buffer, offset)
{
	var sign, exponent, mantissa, ebits;
	var bytes = [];
 
	if (value === undefined)
		throw (new Error('missing value'));
 
	if (endian === undefined)
		throw (new Error('missing endian'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer'));
 
	if (offset === undefined)
		throw (new Error('missing offset'));
 
 
	if (offset + 7 >= buffer.length)
		throw (new Error('Trying to read beyond buffer length'));
 
	if (isNaN(value)) {
		sign = 0;
		exponent = 0x7ff;
		mantissa = 23;
	} else if (value == Number.POSITIVE_INFINITY) {
		sign = 0;
		exponent = 0x7ff;
		mantissa = 0;
	} else if (value == Number.NEGATIVE_INFINITY) {
		sign = 1;
		exponent = 0x7ff;
		mantissa = 0;
	} else {
		/* Well we have some work to do */
 
		/* Thankfully the sign bit is trivial */
		if (value < 0) {
			sign = 1;
			value = Math.abs(value);
		} else {
			sign = 0;
		}
 
		/* Use the correct function to determine number of bits */
		if (value < 1)
			ebits = fracexp(value);
		else
			ebits = intexp(value);
 
		/*
		 * This is a total hack to determine a denormalized value.
		 * Unfortunately, we sometimes do not get a proper value for
		 * ebits, i.e. we lose the values that would get rounded off.
		 *
		 *
		 * The astute observer may wonder why we would be
		 * multiplying by two Math.pows rather than just summing
		 * them. Well, that's to get around a small bug in the
		 * way v8 seems to implement the function. On occasion
		 * doing:
		 *
		 * foo * Math.pow(2, 1023 + 51)
		 *
		 * Causes us to overflow to infinity, where as doing:
		 *
		 * foo * Math.pow(2, 1023) * Math.pow(2, 51)
		 *
		 * Does not cause us to overflow. Go figure.
		 *
		 */
		if (value <= 2.225073858507201e-308 || ebits <= -1023) {
			exponent = 0;
			mantissa = value * Math.pow(2, 1023) * Math.pow(2, 51);
			mantissa %= Math.pow(2, 52);
		} else {
			/*
			 * We might have gotten fucked by our floating point
			 * logarithm magic. This is rather crappy, but that's
			 * our luck. If we just had a log base 2 or access to
			 * the stupid underlying representation this would have
			 * been much easier and we wouldn't have such stupid
			 * kludges or hacks.
			 */
			if (ebits > 1023)
				ebits = 1023;
			exponent = 1023 + ebits;
			mantissa = value * Math.pow(2, -ebits);
			mantissa *= Math.pow(2, 52);
			mantissa %= Math.pow(2, 52);
		}
	}
 
	/* Fill the bytes in backwards to deal with the size issues */
	bytes[7] = mantissa & 0xff;
	bytes[6] = (mantissa >>> 8) & 0xff;
	bytes[5] = (mantissa >>> 16) & 0xff;
	mantissa = (mantissa - (mantissa & 0xffffff)) / Math.pow(2, 24);
	bytes[4] = mantissa & 0xff;
	bytes[3] = (mantissa >>> 8) & 0xff;
	bytes[2] = (mantissa >>> 16) & 0xff;
	bytes[1] = (exponent & 0x00f) << 4 | mantissa >>> 24;
	bytes[0] = (sign << 7) | (exponent & 0x7f0) >>> 4;
 
	if (endian == 'big') {
		buffer[offset] = bytes[0];
		buffer[offset+1] = bytes[1];
		buffer[offset+2] = bytes[2];
		buffer[offset+3] = bytes[3];
		buffer[offset+4] = bytes[4];
		buffer[offset+5] = bytes[5];
		buffer[offset+6] = bytes[6];
		buffer[offset+7] = bytes[7];
	} else {
		buffer[offset+7] = bytes[0];
		buffer[offset+6] = bytes[1];
		buffer[offset+5] = bytes[2];
		buffer[offset+4] = bytes[3];
		buffer[offset+3] = bytes[4];
		buffer[offset+2] = bytes[5];
		buffer[offset+1] = bytes[6];
		buffer[offset] = bytes[7];
	}
}
 
/*
 * Actually export our work above. One might argue that we shouldn't expose
 * these interfaces and just force people to use the higher level abstractions
 * around this work. However, unlike say other libraries we've come across, this
 * interface has several properties: it makes sense, it's simple, and it's
 * useful.
 */
exports.ruint8 = ruint8;
exports.ruint16 = ruint16;
exports.ruint32 = ruint32;
exports.ruint64 = ruint64;
exports.wuint8 = wuint8;
exports.wuint16 = wuint16;
exports.wuint32 = wuint32;
exports.wuint64 = wuint64;
 
exports.rsint8 = rsint8;
exports.rsint16 = rsint16;
exports.rsint32 = rsint32;
exports.rsint64 = rsint64;
exports.wsint8 = wsint8;
exports.wsint16 = wsint16;
exports.wsint32 = wsint32;
exports.wsint64 = wsint64;
 
exports.rfloat = rfloat;
exports.rdouble = rdouble;
exports.wfloat = wfloat;
exports.wdouble = wdouble;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ctype.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/http-signature/node_modules/ctype/ctype.js

Statements: 19.63% (74 / 377)      Branches: 0% (0 / 159)      Functions: 0% (0 / 46)      Lines: 19.68% (74 / 376)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946                                                                          1 1 1                   1                                     1           1           1           1           1           1           1           1           1           1                 1             1                     1           1           1           1           1           1           1           1           1           1                 1                         1                                               1                                 1                                                                             1                                                                                                                                                                     1                                                                         1                       1                           1                                                                                           1                                             1                                                     1                                                               1                                                                                       1                                     1                                                                             1                                               1                                             1                                                           1                                                             1                                                             1                                                                                       1                                                   1                           1                       1 1 1   1   1 1 1 1 1 1 1 1   1 1 1 1 1 1 1 1   1 1 1 1    
/*
 * rm - Feb 2011
 * ctype.js
 *
 * This module provides a simple abstraction towards reading and writing
 * different types of binary data. It is designed to use ctio.js and provide a
 * richer and more expressive API on top of it.
 *
 * By default we support the following as built in basic types:
 *	int8_t
 *	int16_t
 *	int32_t
 *	uint8_t
 *	uint16_t
 *	uint32_t
 *	uint64_t
 *	float
 *	double
 *	char
 *	char[]
 *
 * Each type is returned as a Number, with the exception of char and char[]
 * which are returned as Node Buffers. A char is considered a uint8_t.
 *
 * Requests to read and write data are specified as an array of JSON objects.
 * This is also the same way that one declares structs. Even if just a single
 * value is requested, it must be done as a struct. The array order determines
 * the order that we try and read values. Each entry has the following format
 * with values marked with a * being optional.
 *
 * { key: { type: /type/, value*: /value/, offset*: /offset/ }
 *
 * If offset is defined, we lseek(offset, SEEK_SET) before reading the next
 * value. Value is defined when we're writing out data, otherwise it's ignored.
 *
 */
 
var mod_ctf = require('./ctf.js');
var mod_ctio = require('./ctio.js');
var mod_assert = require('assert');
 
/*
 * This is the set of basic types that we support.
 *
 *	read		The function to call to read in a value from a buffer
 *
 *	write		The function to call to write a value to a buffer
 *
 */
var deftypes = {
    'uint8_t':  { read: ctReadUint8, write: ctWriteUint8 },
    'uint16_t': { read: ctReadUint16, write: ctWriteUint16 },
    'uint32_t': { read: ctReadUint32, write: ctWriteUint32 },
    'uint64_t': { read: ctReadUint64, write: ctWriteUint64 },
    'int8_t': { read: ctReadSint8, write: ctWriteSint8 },
    'int16_t': { read: ctReadSint16, write: ctWriteSint16 },
    'int32_t': { read: ctReadSint32, write: ctWriteSint32 },
    'int64_t': { read: ctReadSint64, write: ctWriteSint64 },
    'float': { read: ctReadFloat, write: ctWriteFloat },
    'double': { read: ctReadDouble, write: ctWriteDouble },
    'char': { read: ctReadChar, write: ctWriteChar },
    'char[]': { read: ctReadCharArray, write: ctWriteCharArray }
};
 
/*
 * The following are wrappers around the CType IO low level API. They encode
 * knowledge about the size and return something in the expected format.
 */
function ctReadUint8(endian, buffer, offset)
{
	var val = mod_ctio.ruint8(buffer, endian, offset);
	return ({ value: val, size: 1 });
}
 
function ctReadUint16(endian, buffer, offset)
{
	var val = mod_ctio.ruint16(buffer, endian, offset);
	return ({ value: val, size: 2 });
}
 
function ctReadUint32(endian, buffer, offset)
{
	var val = mod_ctio.ruint32(buffer, endian, offset);
	return ({ value: val, size: 4 });
}
 
function ctReadUint64(endian, buffer, offset)
{
	var val = mod_ctio.ruint64(buffer, endian, offset);
	return ({ value: val, size: 8 });
}
 
function ctReadSint8(endian, buffer, offset)
{
	var val = mod_ctio.rsint8(buffer, endian, offset);
	return ({ value: val, size: 1 });
}
 
function ctReadSint16(endian, buffer, offset)
{
	var val = mod_ctio.rsint16(buffer, endian, offset);
	return ({ value: val, size: 2 });
}
 
function ctReadSint32(endian, buffer, offset)
{
	var val = mod_ctio.rsint32(buffer, endian, offset);
	return ({ value: val, size: 4 });
}
 
function ctReadSint64(endian, buffer, offset)
{
	var val = mod_ctio.rsint64(buffer, endian, offset);
	return ({ value: val, size: 8 });
}
 
function ctReadFloat(endian, buffer, offset)
{
	var val = mod_ctio.rfloat(buffer, endian, offset);
	return ({ value: val, size: 4 });
}
 
function ctReadDouble(endian, buffer, offset)
{
	var val = mod_ctio.rdouble(buffer, endian, offset);
	return ({ value: val, size: 8 });
}
 
/*
 * Reads a single character into a node buffer
 */
function ctReadChar(endian, buffer, offset)
{
	var res = new Buffer(1);
	res[0] = mod_ctio.ruint8(buffer, endian, offset);
	return ({ value: res, size: 1 });
}
 
function ctReadCharArray(length, endian, buffer, offset)
{
	var ii;
	var res = new Buffer(length);
 
	for (ii = 0; ii < length; ii++)
		res[ii] = mod_ctio.ruint8(buffer, endian, offset + ii);
 
	return ({ value: res, size: length });
}
 
function ctWriteUint8(value, endian, buffer, offset)
{
	mod_ctio.wuint8(value, endian, buffer, offset);
	return (1);
}
 
function ctWriteUint16(value, endian, buffer, offset)
{
	mod_ctio.wuint16(value, endian, buffer, offset);
	return (2);
}
 
function ctWriteUint32(value, endian, buffer, offset)
{
	mod_ctio.wuint32(value, endian, buffer, offset);
	return (4);
}
 
function ctWriteUint64(value, endian, buffer, offset)
{
	mod_ctio.wuint64(value, endian, buffer, offset);
	return (8);
}
 
function ctWriteSint8(value, endian, buffer, offset)
{
	mod_ctio.wsint8(value, endian, buffer, offset);
	return (1);
}
 
function ctWriteSint16(value, endian, buffer, offset)
{
	mod_ctio.wsint16(value, endian, buffer, offset);
	return (2);
}
 
function ctWriteSint32(value, endian, buffer, offset)
{
	mod_ctio.wsint32(value, endian, buffer, offset);
	return (4);
}
 
function ctWriteSint64(value, endian, buffer, offset)
{
	mod_ctio.wsint64(value, endian, buffer, offset);
	return (8);
}
 
function ctWriteFloat(value, endian, buffer, offset)
{
	mod_ctio.wfloat(value, endian, buffer, offset);
	return (4);
}
 
function ctWriteDouble(value, endian, buffer, offset)
{
	mod_ctio.wdouble(value, endian, buffer, offset);
	return (8);
}
 
/*
 * Writes a single character into a node buffer
 */
function ctWriteChar(value, endian, buffer, offset)
{
	if (!(value instanceof Buffer))
		throw (new Error('Input must be a buffer'));
 
	mod_ctio.ruint8(value[0], endian, buffer, offset);
	return (1);
}
 
/*
 * We're going to write 0s into the buffer if the string is shorter than the
 * length of the array.
 */
function ctWriteCharArray(value, length, endian, buffer, offset)
{
	var ii;
 
	if (!(value instanceof Buffer))
		throw (new Error('Input must be a buffer'));
 
	if (value.length > length)
		throw (new Error('value length greater than array length'));
 
	for (ii = 0; ii < value.length && ii < length; ii++)
		mod_ctio.wuint8(value[ii], endian, buffer, offset + ii);
 
	for (; ii < length; ii++)
		mod_ctio.wuint8(0, endian, offset + ii);
 
 
	return (length);
}
 
/*
 * Each parser has their own set of types. We want to make sure that they each
 * get their own copy as they may need to modify it.
 */
function ctGetBasicTypes()
{
	var ret = {};
	var key;
	for (key in deftypes)
		ret[key] = deftypes[key];
 
	return (ret);
}
 
/*
 * Given a string in the form of type[length] we want to split this into an
 * object that extracts that information. We want to note that we could possibly
 * have nested arrays so this should only check the furthest one. It may also be
 * the case that we have no [] pieces, in which case we just return the current
 * type.
 */
function ctParseType(str)
{
	var begInd, endInd;
	var type, len;
	if (typeof (str) != 'string')
		throw (new Error('type must be a Javascript string'));
 
	endInd = str.lastIndexOf(']');
	if (endInd == -1) {
		if (str.lastIndexOf('[') != -1)
			throw (new Error('found invalid type with \'[\' but ' +
			    'no corresponding \']\''));
 
		return ({ type: str });
	}
 
	begInd = str.lastIndexOf('[');
	if (begInd == -1)
		throw (new Error('found invalid type with \']\' but ' +
		    'no corresponding \'[\''));
 
	if (begInd >= endInd)
		throw (new Error('malformed type, \']\' appears before \'[\''));
 
	type = str.substring(0, begInd);
	len = str.substring(begInd + 1, endInd);
 
	return ({ type: type, len: len });
}
 
/*
 * Given a request validate that all of the fields for it are valid and make
 * sense. This includes verifying the following notions:
 *  - Each type requested is present in types
 *  - Only allow a name for a field to be specified once
 *  - If an array is specified, validate that the requested field exists and
 *    comes before it.
 *  - If fields is defined, check that each entry has the occurrence of field
 */
function ctCheckReq(def, types, fields)
{
	var ii, jj;
	var req, keys, key;
	var found = {};
 
	if (!(def instanceof Array))
		throw (new Error('definition is not an array'));
 
	if (def.length === 0)
		throw (new Error('definition must have at least one element'));
 
	for (ii = 0; ii < def.length; ii++) {
		req = def[ii];
		if (!(req instanceof Object))
			throw (new Error('definition must be an array of' +
			    'objects'));
 
		keys = Object.keys(req);
		if (keys.length != 1)
			throw (new Error('definition entry must only have ' +
			    'one key'));
 
		if (keys[0] in found)
			throw (new Error('Specified name already ' +
			    'specified: ' + keys[0]));
 
		if (!('type' in req[keys[0]]))
			throw (new Error('missing required type definition'));
 
		key = ctParseType(req[keys[0]]['type']);
 
		/*
		 * We may have nested arrays, we need to check the validity of
		 * the types until the len field is undefined in key. However,
		 * each time len is defined we need to verify it is either an
		 * integer or corresponds to an already seen key.
		 */
		while (key['len'] !== undefined) {
			if (isNaN(parseInt(key['len'], 10))) {
				if (!(key['len'] in found))
					throw (new Error('Given an array ' +
					    'length without a matching type'));
 
			}
 
			key = ctParseType(key['type']);
		}
 
		/* Now we can validate if the type is valid */
		if (!(key['type'] in types))
			throw (new Error('type not found or typdefed: ' +
			    key['type']));
 
		/* Check for any required fields */
		if (fields !== undefined) {
			for (jj = 0; jj < fields.length; jj++) {
				if (!(fields[jj] in req[keys[0]]))
					throw (new Error('Missing required ' +
					    'field: ' + fields[jj]));
			}
		}
 
		found[keys[0]] = true;
	}
}
 
 
/*
 * Create a new instance of the parser. Each parser has its own store of
 * typedefs and endianness. Conf is an object with the following required
 * values:
 *
 *	endian		Either 'big' or 'little' do determine the endianness we
 *			want to read from or write to.
 *
 * And the following optional values:
 *
 * 	char-type	Valid options here are uint8 and int8. If uint8 is
 * 			specified this changes the default behavior of a single
 * 			char from being a buffer of a single character to being
 * 			a uint8_t. If int8, it becomes an int8_t instead.
 */
function CTypeParser(conf)
{
	if (!conf) throw (new Error('missing required argument'));
 
	if (!('endian' in conf))
		throw (new Error('missing required endian value'));
 
	if (conf['endian'] != 'big' && conf['endian'] != 'little')
		throw (new Error('Invalid endian type'));
 
	if ('char-type' in conf && (conf['char-type'] != 'uint8' &&
	    conf['char-type'] != 'int8'))
		throw (new Error('invalid option for char-type: ' +
		    conf['char-type']));
 
	this.endian = conf['endian'];
	this.types = ctGetBasicTypes();
 
	/*
	 * There may be a more graceful way to do this, but this will have to
	 * serve.
	 */
	if ('char-type' in conf && conf['char-type'] == 'uint8')
		this.types['char'] = this.types['uint8_t'];
 
	if ('char-type' in conf && conf['char-type'] == 'int8')
		this.types['char'] = this.types['int8_t'];
}
 
/*
 * Sets the current endian value for the Parser. If the value is not valid,
 * throws an Error.
 *
 *	endian		Either 'big' or 'little' do determine the endianness we
 *			want to read from or write to.
 *
 */
CTypeParser.prototype.setEndian = function (endian)
{
	if (endian != 'big' && endian != 'little')
		throw (new Error('invalid endian type, must be big or ' +
		    'little'));
 
	this.endian = endian;
};
 
/*
 * Returns the current value of the endian value for the parser.
 */
CTypeParser.prototype.getEndian = function ()
{
	return (this.endian);
};
 
/*
 * A user has requested to add a type, let us honor their request. Yet, if their
 * request doth spurn us, send them unto the Hells which Dante describes.
 *
 * 	name		The string for the type definition we're adding
 *
 *	value		Either a string that is a type/array name or an object
 *			that describes a struct.
 */
CTypeParser.prototype.typedef = function (name, value)
{
	var type;
 
	if (name === undefined)
		throw (new (Error('missing required typedef argument: name')));
 
	if (value === undefined)
		throw (new (Error('missing required typedef argument: value')));
 
	if (typeof (name) != 'string')
		throw (new (Error('the name of a type must be a string')));
 
	type = ctParseType(name);
 
	if (type['len'] !== undefined)
		throw (new Error('Cannot have an array in the typedef name'));
 
	if (name in this.types)
		throw (new Error('typedef name already present: ' + name));
 
	if (typeof (value) != 'string' && !(value instanceof Array))
		throw (new Error('typedef value must either be a string or ' +
		    'struct'));
 
	if (typeof (value) == 'string') {
		type = ctParseType(value);
		if (type['len'] !== undefined) {
			if (isNaN(parseInt(type['len'], 10)))
				throw (new (Error('typedef value must use ' +
				    'fixed size array when outside of a ' +
				    'struct')));
		}
 
		this.types[name] = value;
	} else {
		/* We have a struct, validate it */
		ctCheckReq(value, this.types);
		this.types[name] = value;
	}
};
 
/*
 * Include all of the typedefs, but none of the built in types. This should be
 * treated as read-only.
 */
CTypeParser.prototype.lstypes = function ()
{
	var key;
	var ret = {};
 
	for (key in this.types) {
		if (key in deftypes)
			continue;
		ret[key] = this.types[key];
	}
 
	return (ret);
};
 
/*
 * Given a type string that may have array types that aren't numbers, try and
 * fill them in from the values object. The object should be of the format where
 * indexing into it should return a number for that type.
 *
 *	str		The type string
 *
 *	values		An object that can be used to fulfill type information
 */
function ctResolveArray(str, values)
{
	var ret = '';
	var type = ctParseType(str);
 
	while (type['len'] !== undefined) {
		if (isNaN(parseInt(type['len'], 10))) {
			if (typeof (values[type['len']]) != 'number')
				throw (new Error('cannot sawp in non-number ' +
				    'for array value'));
			ret = '[' + values[type['len']] + ']' + ret;
		} else {
			ret = '[' + type['len'] + ']' + ret;
		}
		type = ctParseType(type['type']);
	}
 
	ret = type['type'] + ret;
 
	return (ret);
}
 
/*
 * [private] Either the typedef resolves to another type string or to a struct.
 * If it resolves to a struct, we just pass it off to read struct. If not, we
 * can just pass it off to read entry.
 */
CTypeParser.prototype.resolveTypedef = function (type, dispatch, buffer,
    offset, value)
{
	var pt;
 
	mod_assert.ok(type in this.types);
	if (typeof (this.types[type]) == 'string') {
		pt = ctParseType(this.types[type]);
		if (dispatch == 'read')
			return (this.readEntry(pt, buffer, offset));
		else if (dispatch == 'write')
			return (this.writeEntry(value, pt, buffer, offset));
		else
			throw (new Error('invalid dispatch type to ' +
			    'resolveTypedef'));
	} else {
		if (dispatch == 'read')
			return (this.readStruct(this.types[type], buffer,
			    offset));
		else if (dispatch == 'write')
			return (this.writeStruct(value, this.types[type],
			    buffer, offset));
		else
			throw (new Error('invalid dispatch type to ' +
			    'resolveTypedef'));
	}
 
};
 
/*
 * [private] Try and read in the specific entry.
 */
CTypeParser.prototype.readEntry = function (type, buffer, offset)
{
	var parse, len;
 
	/*
	 * Because we want to special case char[]s this is unfortunately
	 * a bit uglier than it really should be. We want to special
	 * case char[]s so that we return a node buffer, thus they are a
	 * first class type where as all other arrays just call into a
	 * generic array routine which calls their data-specific routine
	 * the specified number of times.
	 *
	 * The valid dispatch options we have are:
	 *  - Array and char => char[] handler
	 *  - Generic array handler
	 *  - Generic typedef handler
	 *  - Basic type handler
	 */
	if (type['len'] !== undefined) {
		len = parseInt(type['len'], 10);
		if (isNaN(len))
			throw (new Error('somehow got a non-numeric length'));
 
		if (type['type'] == 'char')
			parse = this.types['char[]']['read'](len,
			    this.endian, buffer, offset);
		else
			parse = this.readArray(type['type'],
			    len, buffer, offset);
	} else {
		if (type['type'] in deftypes)
			parse = this.types[type['type']]['read'](this.endian,
			    buffer, offset);
		else
			parse = this.resolveTypedef(type['type'], 'read',
			    buffer, offset);
	}
 
	return (parse);
};
 
/*
 * [private] Read an array of data
 */
CTypeParser.prototype.readArray = function (type, length, buffer, offset)
{
	var ii, ent, pt;
	var baseOffset = offset;
	var ret = new Array(length);
	pt = ctParseType(type);
 
	for (ii = 0; ii < length; ii++) {
		ent = this.readEntry(pt, buffer, offset);
		offset += ent['size'];
		ret[ii] = ent['value'];
	}
 
	return ({ value: ret, size: offset - baseOffset });
};
 
/*
 * [private] Read a single struct in.
 */
CTypeParser.prototype.readStruct = function (def, buffer, offset)
{
	var parse, ii, type, entry, key;
	var baseOffset = offset;
	var ret = {};
 
	/* Walk it and handle doing what's necessary */
	for (ii = 0; ii < def.length; ii++) {
		key = Object.keys(def[ii])[0];
		entry = def[ii][key];
 
		/* Resolve all array values */
		type = ctParseType(ctResolveArray(entry['type'], ret));
 
		if ('offset' in entry)
			offset = baseOffset + entry['offset'];
 
		parse = this.readEntry(type, buffer, offset);
 
		offset += parse['size'];
		ret[key] = parse['value'];
	}
 
	return ({ value: ret, size: (offset-baseOffset)});
};
 
/*
 * This is what we were born to do. We read the data from a buffer and return it
 * in an object whose keys match the values from the object.
 *
 *	def		The array definition of the data to read in
 *
 *	buffer		The buffer to read data from
 *
 *	offset		The offset to start writing to
 *
 * Returns an object where each key corresponds to an entry in def and the value
 * is the read value.
 */
CTypeParser.prototype.readData = function (def, buffer, offset)
{
	/* Sanity check for arguments */
	if (def === undefined)
		throw (new Error('missing definition for what we should be' +
		    'parsing'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer for what we should be ' +
		    'parsing'));
 
	if (offset === undefined)
		throw (new Error('missing offset for what we should be ' +
		    'parsing'));
 
	/* Sanity check the object definition */
	ctCheckReq(def, this.types);
 
	return (this.readStruct(def, buffer, offset)['value']);
};
 
/*
 * [private] Write out an array of data
 */
CTypeParser.prototype.writeArray = function (value, type, length, buffer,
    offset)
{
	var ii, pt;
	var baseOffset = offset;
	if (!(value instanceof Array))
		throw (new Error('asked to write an array, but value is not ' +
		    'an array'));
 
	if (value.length != length)
		throw (new Error('asked to write array of length ' + length +
		    ' but that does not match value length: ' + value.length));
 
	pt = ctParseType(type);
	for (ii = 0; ii < length; ii++)
		offset += this.writeEntry(value[ii], pt, buffer, offset);
 
	return (offset - baseOffset);
};
 
/*
 * [private] Write the specific entry
 */
CTypeParser.prototype.writeEntry = function (value, type, buffer, offset)
{
	var len, ret;
 
	if (type['len'] !== undefined) {
		len = parseInt(type['len'], 10);
		if (isNaN(len))
			throw (new Error('somehow got a non-numeric length'));
 
		if (type['type'] == 'char')
			ret = this.types['char[]']['write'](value, len,
			    this.endian, buffer, offset);
		else
			ret = this.writeArray(value, type['type'],
			    len, buffer, offset);
	} else {
		if (type['type'] in deftypes)
			ret = this.types[type['type']]['write'](value,
			    this.endian, buffer, offset);
		else
			ret = this.resolveTypedef(type['type'], 'write',
			    buffer, offset, value);
	}
 
	return (ret);
};
 
/*
 * [private] Write a single struct out.
 */
CTypeParser.prototype.writeStruct = function (value, def, buffer, offset)
{
	var ii, entry, type, key;
	var baseOffset = offset;
	var vals = {};
 
	for (ii = 0; ii < def.length; ii++) {
		key = Object.keys(def[ii])[0];
		entry = def[ii][key];
 
		type = ctParseType(ctResolveArray(entry['type'], vals));
 
		if ('offset' in entry)
			offset = baseOffset + entry['offset'];
 
		offset += this.writeEntry(value[ii], type, buffer, offset);
		/* Now that we've written it out, we can use it for arrays */
		vals[key] = value[ii];
	}
 
	return (offset);
};
 
/*
 * Unfortunately, we're stuck with the sins of an initial poor design. Because
 * of that, we are going to have to support the old way of writing data via
 * writeData. There we insert the values that you want to write into the
 * definition. A little baroque. Internally, we use the new model. So we need to
 * just get those values out of there. But to maintain the principle of least
 * surprise, we're not going to modify the input data.
 */
function getValues(def)
{
	var ii, out, key;
	out = [];
	for (ii = 0; ii < def.length; ii++) {
		key = Object.keys(def[ii])[0];
		mod_assert.ok('value' in def[ii][key]);
		out.push(def[ii][key]['value']);
	}
 
	return (out);
}
 
/*
 * This is the second half of what we were born to do, write out the data
 * itself. Historically this function required you to put your values in the
 * definition section. This was not the smartest thing to do and a bit of an
 * oversight to be honest. As such, this function now takes a values argument.
 * If values is non-null and non-undefined, it will be used to determine the
 * values. This means that the old method is still supported, but is no longer
 * acceptable.
 *
 *	def		The array definition of the data to write out with
 *			values
 *
 *	buffer		The buffer to write to
 *
 *	offset		The offset in the buffer to write to
 *
 *	values		An array of values to write.
 */
CTypeParser.prototype.writeData = function (def, buffer, offset, values)
{
	var hv;
 
	if (def === undefined)
		throw (new Error('missing definition for what we should be' +
		    'parsing'));
 
	if (buffer === undefined)
		throw (new Error('missing buffer for what we should be ' +
		    'parsing'));
 
	if (offset === undefined)
		throw (new Error('missing offset for what we should be ' +
		    'parsing'));
 
	hv = (values != null && values != undefined);
	if (hv) {
		if (!Array.isArray(values))
			throw (new Error('missing values for writing'));
		ctCheckReq(def, this.types);
	} else {
		ctCheckReq(def, this.types, [ 'value' ]);
	}
 
	this.writeStruct(hv ? values : getValues(def), def, buffer, offset);
};
 
/*
 * Functions to go to and from 64 bit numbers in a way that is compatible with
 * Javascript limitations. There are two sets. One where the user is okay with
 * an approximation and one where they are definitely not okay with an
 * approximation.
 */
 
/*
 * Attempts to convert an array of two integers returned from rsint64 / ruint64
 * into an absolute 64 bit number. If however the value would exceed 2^52 this
 * will instead throw an error. The mantissa in a double is a 52 bit number and
 * rather than potentially give you a value that is an approximation this will
 * error. If you would rather an approximation, please see toApprox64.
 *
 *	val		An array of two 32-bit integers
 */
function toAbs64(val)
{
	if (val === undefined)
		throw (new Error('missing required arg: value'));
 
	if (!Array.isArray(val))
		throw (new Error('value must be an array'));
 
	if (val.length != 2)
		throw (new Error('value must be an array of length 2'));
 
	/* We have 20 bits worth of precision in this range */
	if (val[0] >= 0x100000)
		throw (new Error('value would become approximated'));
 
	return (val[0] * Math.pow(2, 32) + val[1]);
}
 
/*
 * Will return the 64 bit value as returned in an array from rsint64 / ruint64
 * to a value as close as it can. Note that Javascript stores all numbers as a
 * double and the mantissa only has 52 bits. Thus this version may approximate
 * the value.
 *
 *	val		An array of two 32-bit integers
 */
function toApprox64(val)
{
	if (val === undefined)
		throw (new Error('missing required arg: value'));
 
	if (!Array.isArray(val))
		throw (new Error('value must be an array'));
 
	if (val.length != 2)
		throw (new Error('value must be an array of length 2'));
 
	return (Math.pow(2, 32) * val[0] + val[1]);
}
 
function parseCTF(json, conf)
{
	var ctype = new CTypeParser(conf);
	mod_ctf.ctfParseJson(json, ctype);
 
	return (ctype);
}
 
/*
 * Export the few things we actually want to. Currently this is just the CType
 * Parser and ctio.
 */
exports.Parser = CTypeParser;
exports.toAbs64 = toAbs64;
exports.toApprox64 = toApprox64;
 
exports.parseCTF = parseCTF;
 
exports.ruint8 = mod_ctio.ruint8;
exports.ruint16 = mod_ctio.ruint16;
exports.ruint32 = mod_ctio.ruint32;
exports.ruint64 = mod_ctio.ruint64;
exports.wuint8 = mod_ctio.wuint8;
exports.wuint16 = mod_ctio.wuint16;
exports.wuint32 = mod_ctio.wuint32;
exports.wuint64 = mod_ctio.wuint64;
 
exports.rsint8 = mod_ctio.rsint8;
exports.rsint16 = mod_ctio.rsint16;
exports.rsint32 = mod_ctio.rsint32;
exports.rsint64 = mod_ctio.rsint64;
exports.wsint8 = mod_ctio.wsint8;
exports.wsint16 = mod_ctio.wsint16;
exports.wsint32 = mod_ctio.wsint32;
exports.wsint64 = mod_ctio.wsint64;
 
exports.rfloat = mod_ctio.rfloat;
exports.rdouble = mod_ctio.rdouble;
exports.wfloat = mod_ctio.wfloat;
exports.wdouble = mod_ctio.wdouble;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/isstream/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/isstream/

Statements: 69.23% (9 / 13)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 69.23% (9 / 13)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/isstream/
File Statements Branches Functions Lines
isstream.js 69.23% (9 / 13) 0% (0 / 8) 0% (0 / 4) 69.23% (9 / 13)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/isstream/isstream.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/isstream/isstream.js

Statements: 69.23% (9 / 13)      Branches: 0% (0 / 8)      Functions: 0% (0 / 4)      Lines: 69.23% (9 / 13)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 291     1         1         1         1         1 1 1 1    
var stream = require('stream')
 
 
function isStream (obj) {
  return obj instanceof stream.Stream
}
 
 
function isReadable (obj) {
  return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
}
 
 
function isWritable (obj) {
  return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
}
 
 
function isDuplex (obj) {
  return isReadable(obj) && isWritable(obj)
}
 
 
module.exports            = isStream
module.exports.isReadable = isReadable
module.exports.isWritable = isWritable
module.exports.isDuplex   = isDuplex
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/json-stringify-safe/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/json-stringify-safe/

Statements: 20% (4 / 20)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 23.53% (4 / 17)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/json-stringify-safe/
File Statements Branches Functions Lines
stringify.js 20% (4 / 20) 0% (0 / 14) 0% (0 / 4) 23.53% (4 / 17)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/json-stringify-safe/stringify.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/json-stringify-safe/stringify.js

Statements: 20% (4 / 20)      Branches: 0% (0 / 14)      Functions: 0% (0 / 4)      Lines: 23.53% (4 / 17)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 291 1   1       1                                          
exports = module.exports = stringify
exports.getSerialize = serializer
 
function stringify(obj, replacer, spaces, cycleReplacer) {
  return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
}
 
function serializer(replacer, cycleReplacer) {
  var stack = [], keys = []
 
  if (cycleReplacer == null) cycleReplacer = function(key, value) {
    if (stack[0] === value) return "[Circular ~]"
    return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
  }
 
  return function(key, value) {
    if (stack.length > 0) {
      var thisPos = stack.indexOf(this)
      ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
      ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
      if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
    }
    else stack.push(value)
 
    return replacer == null ? value : replacer.call(this, key, value)
  }
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/
File Statements Branches Functions Lines
index.js 33.33% (16 / 48) 10% (4 / 40) 33.33% (2 / 6) 41.67% (15 / 36)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/index.js

Statements: 33.33% (16 / 48)      Branches: 10% (4 / 40)      Functions: 33.33% (2 / 6)      Lines: 41.67% (15 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65  1     1   1   1 1799 1799 1799 789 789 1018       1               1                     1                     1         1                      
 
var db = require('mime-db')
 
// types[extension] = type
exports.types = Object.create(null)
// extensions[type] = [extensions]
exports.extensions = Object.create(null)
 
Object.keys(db).forEach(function (name) {
  var mime = db[name]
  var exts = mime.extensions
  if (!exts || !exts.length) return
  exports.extensions[name] = exts
  exts.forEach(function (ext) {
    exports.types[ext] = name
  })
})
 
exports.lookup = function (string) {
  if (!string || typeof string !== "string") return false
  // remove any leading paths, though we should just use path.basename
  string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
  if (!string) return false
  return exports.types[string] || false
}
 
exports.extension = function (type) {
  if (!type || typeof type !== "string") return false
  // to do: use media-typer
  type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
  if (!type) return false
  var exts = exports.extensions[type[1].toLowerCase()]
  if (!exts || !exts.length) return false
  return exts[0]
}
 
// type has to be an exact mime type
exports.charset = function (type) {
  var mime = db[type]
  if (mime && mime.charset) return mime.charset
 
  // default text/* to utf-8
  if (/^text\//.test(type)) return 'UTF-8'
 
  return false
}
 
// backwards compatibility
exports.charsets = {
  lookup: exports.charset
}
 
// to do: maybe use set-type module or something
exports.contentType = function (type) {
  if (!type || typeof type !== "string") return false
  if (!~type.indexOf('/')) type = exports.lookup(type)
  if (!type) return false
  if (!~type.indexOf('charset')) {
    var charset = exports.charset(type)
    if (charset) type += '; charset=' + charset.toLowerCase()
  }
  return type
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/node_modules/mime-db/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/node_modules/mime-db/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/node_modules/mime-db/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/node_modules/mime-db/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/mime-types/node_modules/mime-db/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13                    1    
/*!
 * mime-db
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */
 
/**
 * Module exports.
 */
 
module.exports = require('./db.json')
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/node-uuid/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/node-uuid/

Statements: 33.02% (35 / 106)      Branches: 14.29% (11 / 77)      Functions: 18.18% (2 / 11)      Lines: 33.01% (34 / 103)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/node-uuid/
File Statements Branches Functions Lines
uuid.js 33.02% (35 / 106) 14.29% (11 / 77) 18.18% (2 / 11) 33.01% (34 / 103)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/node-uuid/uuid.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/node-uuid/uuid.js

Statements: 33.02% (35 / 106)      Branches: 14.29% (11 / 77)      Functions: 18.18% (2 / 11)      Lines: 33.01% (34 / 103)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249          1 1         1         1             1                     1         1 1 1 16 16     1         1     1 1 1 256 256       1                                     1                                   1     1           1     1     1                                                                                                                                                           1                                                     1 1 1 1 1 1   1   1                                        
//     uuid.js
//
//     Copyright (c) 2010-2012 Robert Kieffer
//     MIT License - http://opensource.org/licenses/mit-license.php
 
(function() {
  var _global = this;
 
  // Unique ID creation requires a high quality random # generator.  We feature
  // detect to determine the best RNG source, normalizing to a function that
  // returns 128-bits of randomness, since that's what's usually required
  var _rng;
 
  // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
  //
  // Moderately fast, high quality
  Iif (typeof(_global.require) == 'function') {
    try {
      var _rb = _global.require('crypto').randomBytes;
      _rng = _rb && function() {return _rb(16);};
    } catch(e) {}
  }
 
  Iif (!_rng && _global.crypto && crypto.getRandomValues) {
    // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
    //
    // Moderately fast, high quality
    var _rnds8 = new Uint8Array(16);
    _rng = function whatwgRNG() {
      crypto.getRandomValues(_rnds8);
      return _rnds8;
    };
  }
 
  Eif (!_rng) {
    // Math.random()-based (RNG)
    //
    // If all else fails, use Math.random().  It's fast, but is of unspecified
    // quality.
    var  _rnds = new Array(16);
    _rng = function() {
      for (var i = 0, r; i < 16; i++) {
        if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
        _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
      }
 
      return _rnds;
    };
  }
 
  // Buffer class to use
  var BufferClass = typeof(_global.Buffer) == 'function' ? _global.Buffer : Array;
 
  // Maps for number <-> hex string conversion
  var _byteToHex = [];
  var _hexToByte = {};
  for (var i = 0; i < 256; i++) {
    _byteToHex[i] = (i + 0x100).toString(16).substr(1);
    _hexToByte[_byteToHex[i]] = i;
  }
 
  // **`parse()` - Parse a UUID into it's component bytes**
  function parse(s, buf, offset) {
    var i = (buf && offset) || 0, ii = 0;
 
    buf = buf || [];
    s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
      if (ii < 16) { // Don't overflow!
        buf[i + ii++] = _hexToByte[oct];
      }
    });
 
    // Zero out remaining bytes if string was short
    while (ii < 16) {
      buf[i + ii++] = 0;
    }
 
    return buf;
  }
 
  // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  function unparse(buf, offset) {
    var i = offset || 0, bth = _byteToHex;
    return  bth[buf[i++]] + bth[buf[i++]] +
            bth[buf[i++]] + bth[buf[i++]] + '-' +
            bth[buf[i++]] + bth[buf[i++]] + '-' +
            bth[buf[i++]] + bth[buf[i++]] + '-' +
            bth[buf[i++]] + bth[buf[i++]] + '-' +
            bth[buf[i++]] + bth[buf[i++]] +
            bth[buf[i++]] + bth[buf[i++]] +
            bth[buf[i++]] + bth[buf[i++]];
  }
 
  // **`v1()` - Generate time-based UUID**
  //
  // Inspired by https://github.com/LiosK/UUID.js
  // and http://docs.python.org/library/uuid.html
 
  // random #'s we need to init node and clockseq
  var _seedBytes = _rng();
 
  // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  var _nodeId = [
    _seedBytes[0] | 0x01,
    _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
  ];
 
  // Per 4.2.2, randomize (14 bit) clockseq
  var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
 
  // Previous uuid creation time
  var _lastMSecs = 0, _lastNSecs = 0;
 
  // See https://github.com/broofa/node-uuid for API details
  function v1(options, buf, offset) {
    var i = buf && offset || 0;
    var b = buf || [];
 
    options = options || {};
 
    var clockseq = options.clockseq != null ? options.clockseq : _clockseq;
 
    // UUID timestamps are 100 nano-second units since the Gregorian epoch,
    // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
    // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
    // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
    var msecs = options.msecs != null ? options.msecs : new Date().getTime();
 
    // Per 4.2.1.2, use count of uuid's generated during the current clock
    // cycle to simulate higher resolution clock
    var nsecs = options.nsecs != null ? options.nsecs : _lastNSecs + 1;
 
    // Time since last uuid creation (in msecs)
    var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
 
    // Per 4.2.1.2, Bump clockseq on clock regression
    if (dt < 0 && options.clockseq == null) {
      clockseq = clockseq + 1 & 0x3fff;
    }
 
    // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
    // time interval
    if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
      nsecs = 0;
    }
 
    // Per 4.2.1.2 Throw error if too many uuids are requested
    if (nsecs >= 10000) {
      throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
    }
 
    _lastMSecs = msecs;
    _lastNSecs = nsecs;
    _clockseq = clockseq;
 
    // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
    msecs += 12219292800000;
 
    // `time_low`
    var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
    b[i++] = tl >>> 24 & 0xff;
    b[i++] = tl >>> 16 & 0xff;
    b[i++] = tl >>> 8 & 0xff;
    b[i++] = tl & 0xff;
 
    // `time_mid`
    var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
    b[i++] = tmh >>> 8 & 0xff;
    b[i++] = tmh & 0xff;
 
    // `time_high_and_version`
    b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
    b[i++] = tmh >>> 16 & 0xff;
 
    // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
    b[i++] = clockseq >>> 8 | 0x80;
 
    // `clock_seq_low`
    b[i++] = clockseq & 0xff;
 
    // `node`
    var node = options.node || _nodeId;
    for (var n = 0; n < 6; n++) {
      b[i + n] = node[n];
    }
 
    return buf ? buf : unparse(b);
  }
 
  // **`v4()` - Generate random UUID**
 
  // See https://github.com/broofa/node-uuid for API details
  function v4(options, buf, offset) {
    // Deprecated - 'format' argument, as supported in v1.2
    var i = buf && offset || 0;
 
    if (typeof(options) == 'string') {
      buf = options == 'binary' ? new BufferClass(16) : null;
      options = null;
    }
    options = options || {};
 
    var rnds = options.random || (options.rng || _rng)();
 
    // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
    rnds[6] = (rnds[6] & 0x0f) | 0x40;
    rnds[8] = (rnds[8] & 0x3f) | 0x80;
 
    // Copy bytes to buffer, if provided
    if (buf) {
      for (var ii = 0; ii < 16; ii++) {
        buf[i + ii] = rnds[ii];
      }
    }
 
    return buf || unparse(rnds);
  }
 
  // Export public API
  var uuid = v4;
  uuid.v1 = v1;
  uuid.v4 = v4;
  uuid.parse = parse;
  uuid.unparse = unparse;
  uuid.BufferClass = BufferClass;
 
  Eif (typeof(module) != 'undefined' && module.exports) {
    // Publish as node.js module
    module.exports = uuid;
  } else  if (typeof define === 'function' && define.amd) {
    // Publish as AMD module
    define(function() {return uuid;});
 
 
  } else {
    // Publish as global (in browsers)
    var _previousRoot = _global.uuid;
 
    // **`noConflict()` - (browser only) to reset global 'uuid' var**
    uuid.noConflict = function() {
      _global.uuid = _previousRoot;
      return uuid;
    };
 
    _global.uuid = uuid;
  }
}).call(this);
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/oauth-sign/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/oauth-sign/

Statements: 28.07% (16 / 57)      Branches: 0% (0 / 28)      Functions: 0% (0 / 13)      Lines: 28.07% (16 / 57)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/oauth-sign/
File Statements Branches Functions Lines
index.js 28.07% (16 / 57) 0% (0 / 28) 0% (0 / 13) 28.07% (16 / 57)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/oauth-sign/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/oauth-sign/index.js

Statements: 28.07% (16 / 57)      Branches: 0% (0 / 28)      Functions: 0% (0 / 13)      Lines: 28.07% (16 / 57)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 1361       1       1       1                         1                                 1       1                                                                     1                   1             1                 1                                           1 1 1 1 1    
var crypto = require('crypto')
  , qs = require('querystring')
  ;
 
function sha1 (key, body) {
  return crypto.createHmac('sha1', key).update(body).digest('base64')
}
 
function rsa (key, body) {
  return crypto.createSign("RSA-SHA1").update(body).sign(key, 'base64');
}
 
function rfc3986 (str) {
  return encodeURIComponent(str)
    .replace(/!/g,'%21')
    .replace(/\*/g,'%2A')
    .replace(/\(/g,'%28')
    .replace(/\)/g,'%29')
    .replace(/'/g,'%27')
    ;
}
 
// Maps object to bi-dimensional array
// Converts { foo: 'A', bar: [ 'b', 'B' ]} to
// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
function map (obj) {
  var key, val, arr = []
  for (key in obj) {
    val = obj[key]
    if (Array.isArray(val))
      for (var i = 0; i < val.length; i++)
        arr.push([key, val[i]])
    else if (typeof val === "object")
      for (var prop in val)
        arr.push([key + '[' + prop + ']', val[prop]]);
    else
      arr.push([key, val])
  }
  return arr
}
 
// Compare function for sort
function compare (a, b) {
  return a > b ? 1 : a < b ? -1 : 0
}
 
function generateBase (httpMethod, base_uri, params) {
  // adapted from https://dev.twitter.com/docs/auth/oauth and 
  // https://dev.twitter.com/docs/auth/creating-signature
 
  // Parameter normalization
  // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
  var normalized = map(params)
  // 1.  First, the name and value of each parameter are encoded
  .map(function (p) {
    return [ rfc3986(p[0]), rfc3986(p[1] || '') ]
  })
  // 2.  The parameters are sorted by name, using ascending byte value
  //     ordering.  If two or more parameters share the same name, they
  //     are sorted by their value.
  .sort(function (a, b) {
    return compare(a[0], b[0]) || compare(a[1], b[1])
  })
  // 3.  The name of each parameter is concatenated to its corresponding
  //     value using an "=" character (ASCII code 61) as a separator, even
  //     if the value is empty.
  .map(function (p) { return p.join('=') })
   // 4.  The sorted name/value pairs are concatenated together into a
   //     single string by using an "&" character (ASCII code 38) as
   //     separator.
  .join('&')
 
  var base = [
    rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
    rfc3986(base_uri),
    rfc3986(normalized)
  ].join('&')
 
  return base
}
 
function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) {
  var base = generateBase(httpMethod, base_uri, params)
  var key = [
    consumer_secret || '',
    token_secret || ''
  ].map(rfc3986).join('&')
 
  return sha1(key, base)
}
 
function rsasign (httpMethod, base_uri, params, private_key, token_secret) {
  var base = generateBase(httpMethod, base_uri, params)
  var key = private_key || ''
 
  return rsa(key, base)
}
 
function plaintext (consumer_secret, token_secret) {
  var key = [
    consumer_secret || '',
    token_secret || ''
  ].map(rfc3986).join('&')
 
  return key
}
 
function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
  var method
  var skipArgs = 1
 
  switch (signMethod) {
    case 'RSA-SHA1':
      method = rsasign
      break
    case 'HMAC-SHA1':
      method = hmacsign
      break
    case 'PLAINTEXT':
      method = plaintext
      skipArgs = 4
      break
    default:
     throw new Error("Signature method not supported: " + signMethod)
  }
 
  return method.apply(null, [].slice.call(arguments, skipArgs))
}
 
exports.hmacsign = hmacsign
exports.rsasign = rsasign
exports.plaintext = plaintext
exports.sign = sign
exports.rfc3986 = rfc3986
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/
File Statements Branches Functions Lines
index.js 100% (1 / 1) 100% (0 / 0) 100% (0 / 0) 100% (1 / 1)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/index.js

Statements: 100% (1 / 1)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (1 / 1)      Ignored: none     

1 2 31    
module.exports = require('./lib/');
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/

Statements: 11.52% (25 / 217)      Branches: 1.23% (2 / 163)      Functions: 0% (0 / 16)      Lines: 11.52% (25 / 217)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/
File Statements Branches Functions Lines
index.js 100% (4 / 4) 100% (0 / 0) 100% (0 / 0) 100% (4 / 4)
parse.js 8.33% (6 / 72) 0% (0 / 57) 0% (0 / 4) 8.33% (6 / 72)
stringify.js 7.27% (4 / 55) 0% (0 / 43) 0% (0 / 5) 7.27% (4 / 55)
utils.js 12.79% (11 / 86) 3.17% (2 / 63) 0% (0 / 7) 12.79% (11 / 86)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/index.js

Statements: 100% (4 / 4)      Branches: 100% (0 / 0)      Functions: 100% (0 / 0)      Lines: 100% (4 / 4)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17    1 1         1     1          
// Load modules
 
var Stringify = require('./stringify');
var Parse = require('./parse');
 
 
// Declare internals
 
var internals = {};
 
 
module.exports = {
    stringify: Stringify,
    parse: Parse
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/parse.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/parse.js

Statements: 8.33% (6 / 72)      Branches: 0% (0 / 57)      Functions: 0% (0 / 4)      Lines: 8.33% (6 / 72)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168    1         1                 1                                                                 1                                                                         1                                                                                             1                                                                    
// Load modules
 
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {
    delimiter: '&',
    depth: 5,
    arrayLimit: 20,
    parameterLimit: 1000,
    strictNullHandling: false
};
 
 
internals.parseValues = function (str, options) {
 
    var obj = {};
    var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
 
    for (var i = 0, il = parts.length; i < il; ++i) {
        var part = parts[i];
        var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
 
        if (pos === -1) {
            obj[Utils.decode(part)] = '';
 
            if (options.strictNullHandling) {
                obj[Utils.decode(part)] = null;
            }
        }
        else {
            var key = Utils.decode(part.slice(0, pos));
            var val = Utils.decode(part.slice(pos + 1));
 
            if (!Object.prototype.hasOwnProperty.call(obj, key)) {
                obj[key] = val;
            }
            else {
                obj[key] = [].concat(obj[key]).concat(val);
            }
        }
    }
 
    return obj;
};
 
 
internals.parseObject = function (chain, val, options) {
 
    if (!chain.length) {
        return val;
    }
 
    var root = chain.shift();
 
    var obj;
    if (root === '[]') {
        obj = [];
        obj = obj.concat(internals.parseObject(chain, val, options));
    }
    else {
        obj = Object.create(null);
        var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root;
        var index = parseInt(cleanRoot, 10);
        var indexString = '' + index;
        if (!isNaN(index) &&
            root !== cleanRoot &&
            indexString === cleanRoot &&
            index >= 0 &&
            (options.parseArrays &&
             index <= options.arrayLimit)) {
 
            obj = [];
            obj[index] = internals.parseObject(chain, val, options);
        }
        else {
            obj[cleanRoot] = internals.parseObject(chain, val, options);
        }
    }
 
    return obj;
};
 
 
internals.parseKeys = function (key, val, options) {
 
    if (!key) {
        return;
    }
 
    // Transform dot notation to bracket notation
 
    if (options.allowDots) {
        key = key.replace(/\.([^\.\[]+)/g, '[$1]');
    }
 
    // The regex chunks
 
    var parent = /^([^\[\]]*)/;
    var child = /(\[[^\[\]]*\])/g;
 
    // Get the parent
 
    var segment = parent.exec(key);
 
    // Stash the parent if it exists
 
    var keys = [];
    if (segment[1]) {
        keys.push(segment[1]);
    }
 
    // Loop through children appending to the array until we hit depth
 
    var i = 0;
    while ((segment = child.exec(key)) !== null && i < options.depth) {
 
        ++i;
        keys.push(segment[1]);
    }
 
    // If there's a remainder, just add whatever is left
 
    if (segment) {
        keys.push('[' + key.slice(segment.index) + ']');
    }
 
    return internals.parseObject(keys, val, options);
};
 
 
module.exports = function (str, options) {
 
    if (str === '' ||
        str === null ||
        typeof str === 'undefined') {
 
        return Object.create(null);
    }
 
    options = options || {};
    options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter;
    options.depth = typeof options.depth === 'number' ? options.depth : internals.depth;
    options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit;
    options.parseArrays = options.parseArrays !== false;
    options.allowDots = options.allowDots !== false;
    options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit;
    options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling;
 
 
    var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str;
    var obj = Object.create(null);
 
    // Iterate over the keys and setup the new object
 
    var keys = Object.keys(tempObj);
    for (var i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        var newObj = internals.parseKeys(key, tempObj[key], options);
        obj = Utils.merge(obj, newObj);
    }
 
    return Utils.compact(obj);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/stringify.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/stringify.js

Statements: 7.27% (4 / 55)      Branches: 0% (0 / 43)      Functions: 0% (0 / 5)      Lines: 7.27% (4 / 55)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123    1         1                                       1                                                                                               1                                                                                              
// Load modules
 
var Utils = require('./utils');
 
 
// Declare internals
 
var internals = {
    delimiter: '&',
    arrayPrefixGenerators: {
        brackets: function (prefix, key) {
 
            return prefix + '[]';
        },
        indices: function (prefix, key) {
 
            return prefix + '[' + key + ']';
        },
        repeat: function (prefix, key) {
 
            return prefix;
        }
    },
    strictNullHandling: false
};
 
 
internals.stringify = function (obj, prefix, generateArrayPrefix, strictNullHandling, filter) {
 
    if (typeof filter === 'function') {
        obj = filter(prefix, obj);
    }
    else if (Utils.isBuffer(obj)) {
        obj = obj.toString();
    }
    else if (obj instanceof Date) {
        obj = obj.toISOString();
    }
    else if (obj === null) {
        if (strictNullHandling) {
            return Utils.encode(prefix);
        }
 
        obj = '';
    }
 
    if (typeof obj === 'string' ||
        typeof obj === 'number' ||
        typeof obj === 'boolean') {
 
        return [Utils.encode(prefix) + '=' + Utils.encode(obj)];
    }
 
    var values = [];
 
    if (typeof obj === 'undefined') {
        return values;
    }
 
    var objKeys = Array.isArray(filter) ? filter : Object.keys(obj);
    for (var i = 0, il = objKeys.length; i < il; ++i) {
        var key = objKeys[i];
 
        if (Array.isArray(obj)) {
            values = values.concat(internals.stringify(obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, filter));
        }
        else {
            values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', generateArrayPrefix, strictNullHandling, filter));
        }
    }
 
    return values;
};
 
 
module.exports = function (obj, options) {
 
    options = options || {};
    var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
    var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling;
    var objKeys;
    var filter;
    if (typeof options.filter === 'function') {
        filter = options.filter;
        obj = filter('', obj);
    }
    else if (Array.isArray(options.filter)) {
        objKeys = filter = options.filter;
    }
 
    var keys = [];
 
    if (typeof obj !== 'object' ||
        obj === null) {
 
        return '';
    }
 
    var arrayFormat;
    if (options.arrayFormat in internals.arrayPrefixGenerators) {
        arrayFormat = options.arrayFormat;
    }
    else if ('indices' in options) {
        arrayFormat = options.indices ? 'indices' : 'repeat';
    }
    else {
        arrayFormat = 'indices';
    }
 
    var generateArrayPrefix = internals.arrayPrefixGenerators[arrayFormat];
 
    if (!objKeys) {
        objKeys = Object.keys(obj);
    }
    for (var i = 0, il = objKeys.length; i < il; ++i) {
        var key = objKeys[i];
        keys = keys.concat(internals.stringify(obj[key], key, generateArrayPrefix, strictNullHandling, filter));
    }
 
    return keys.join(delimiter);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/utils.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/qs/lib/utils.js

Statements: 12.79% (11 / 86)      Branches: 3.17% (2 / 63)      Functions: 0% (0 / 7)      Lines: 12.79% (11 / 86)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192          1 1 1 256       1                           1                                                                                               1                 1                                                                                                     1                                                                           1           1                          
// Load modules
 
 
// Declare internals
 
var internals = {};
internals.hexTable = new Array(256);
for (var i = 0; i < 256; ++i) {
    internals.hexTable[i] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase();
}
 
 
exports.arrayToObject = function (source) {
 
    var obj = Object.create(null);
    for (var i = 0, il = source.length; i < il; ++i) {
        if (typeof source[i] !== 'undefined') {
 
            obj[i] = source[i];
        }
    }
 
    return obj;
};
 
 
exports.merge = function (target, source) {
 
    if (!source) {
        return target;
    }
 
    if (typeof source !== 'object') {
        if (Array.isArray(target)) {
            target.push(source);
        }
        else if (typeof target === 'object') {
            target[source] = true;
        }
        else {
            target = [target, source];
        }
 
        return target;
    }
 
    if (typeof target !== 'object') {
        target = [target].concat(source);
        return target;
    }
 
    if (Array.isArray(target) &&
        !Array.isArray(source)) {
 
        target = exports.arrayToObject(target);
    }
 
    var keys = Object.keys(source);
    for (var k = 0, kl = keys.length; k < kl; ++k) {
        var key = keys[k];
        var value = source[key];
 
        if (!target[key]) {
            target[key] = value;
        }
        else {
            target[key] = exports.merge(target[key], value);
        }
    }
 
    return target;
};
 
 
exports.decode = function (str) {
 
    try {
        return decodeURIComponent(str.replace(/\+/g, ' '));
    } catch (e) {
        return str;
    }
};
 
exports.encode = function (str) {
 
    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
    // It has been adapted here for stricter adherence to RFC 3986
    if (str.length === 0) {
        return str;
    }
 
    if (typeof str !== 'string') {
        str = '' + str;
    }
 
    var out = '';
    for (var i = 0, il = str.length; i < il; ++i) {
        var c = str.charCodeAt(i);
 
        if (c === 0x2D || // -
            c === 0x2E || // .
            c === 0x5F || // _
            c === 0x7E || // ~
            (c >= 0x30 && c <= 0x39) || // 0-9
            (c >= 0x41 && c <= 0x5A) || // a-z
            (c >= 0x61 && c <= 0x7A)) { // A-Z
 
            out += str[i];
            continue;
        }
 
        if (c < 0x80) {
            out += internals.hexTable[c];
            continue;
        }
 
        if (c < 0x800) {
            out += internals.hexTable[0xC0 | (c >> 6)] + internals.hexTable[0x80 | (c & 0x3F)];
            continue;
        }
 
        if (c < 0xD800 || c >= 0xE000) {
            out += internals.hexTable[0xE0 | (c >> 12)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)];
            continue;
        }
 
        ++i;
        c = 0x10000 + (((c & 0x3FF) << 10) | (str.charCodeAt(i) & 0x3FF));
        out += internals.hexTable[0xF0 | (c >> 18)] + internals.hexTable[0x80 | ((c >> 12) & 0x3F)] + internals.hexTable[0x80 | ((c >> 6) & 0x3F)] + internals.hexTable[0x80 | (c & 0x3F)];
    }
 
    return out;
};
 
exports.compact = function (obj, refs) {
 
    if (typeof obj !== 'object' ||
        obj === null) {
 
        return obj;
    }
 
    refs = refs || [];
    var lookup = refs.indexOf(obj);
    if (lookup !== -1) {
        return refs[lookup];
    }
 
    refs.push(obj);
 
    if (Array.isArray(obj)) {
        var compacted = [];
 
        for (var i = 0, il = obj.length; i < il; ++i) {
            if (typeof obj[i] !== 'undefined') {
                compacted.push(obj[i]);
            }
        }
 
        return compacted;
    }
 
    var keys = Object.keys(obj);
    for (i = 0, il = keys.length; i < il; ++i) {
        var key = keys[i];
        obj[key] = exports.compact(obj[key], refs);
    }
 
    return obj;
};
 
 
exports.isRegExp = function (obj) {
 
    return Object.prototype.toString.call(obj) === '[object RegExp]';
};
 
 
exports.isBuffer = function (obj) {
 
    if (obj === null ||
        typeof obj === 'undefined') {
 
        return false;
    }
 
    return !!(obj.constructor &&
              obj.constructor.isBuffer &&
              obj.constructor.isBuffer(obj));
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/stringstream/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/stringstream/

Statements: 22.08% (17 / 77)      Branches: 0% (0 / 35)      Functions: 0% (0 / 10)      Lines: 25% (17 / 68)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/stringstream/
File Statements Branches Functions Lines
stringstream.js 22.08% (17 / 77) 0% (0 / 35) 0% (0 / 10) 25% (17 / 68)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/stringstream/stringstream.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/stringstream/stringstream.js

Statements: 22.08% (17 / 77)      Branches: 0% (0 / 35)      Functions: 0% (0 / 10)      Lines: 25% (17 / 68)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 1041 1 1   1 1   1                         1   1                               1             1               1           1       1         1                     1   1             1                              
var util = require('util')
var Stream = require('stream')
var StringDecoder = require('string_decoder').StringDecoder
 
module.exports = StringStream
module.exports.AlignedStringDecoder = AlignedStringDecoder
 
function StringStream(from, to) {
  if (!(this instanceof StringStream)) return new StringStream(from, to)
 
  Stream.call(this)
 
  if (from == null) from = 'utf8'
 
  this.readable = this.writable = true
  this.paused = false
  this.toEncoding = (to == null ? from : to)
  this.fromEncoding = (to == null ? '' : from)
  this.decoder = new AlignedStringDecoder(this.toEncoding)
}
util.inherits(StringStream, Stream)
 
StringStream.prototype.write = function(data) {
  if (!this.writable) {
    var err = new Error('stream not writable')
    err.code = 'EPIPE'
    this.emit('error', err)
    return false
  }
  if (this.fromEncoding) {
    if (Buffer.isBuffer(data)) data = data.toString()
    data = new Buffer(data, this.fromEncoding)
  }
  var string = this.decoder.write(data)
  if (string.length) this.emit('data', string)
  return !this.paused
}
 
StringStream.prototype.flush = function() {
  if (this.decoder.flush) {
    var string = this.decoder.flush()
    if (string.length) this.emit('data', string)
  }
}
 
StringStream.prototype.end = function() {
  if (!this.writable && !this.readable) return
  this.flush()
  this.emit('end')
  this.writable = this.readable = false
  this.destroy()
}
 
StringStream.prototype.destroy = function() {
  this.decoder = null
  this.writable = this.readable = false
  this.emit('close')
}
 
StringStream.prototype.pause = function() {
  this.paused = true
}
 
StringStream.prototype.resume = function () {
  if (this.paused) this.emit('drain')
  this.paused = false
}
 
function AlignedStringDecoder(encoding) {
  StringDecoder.call(this, encoding)
 
  switch (this.encoding) {
    case 'base64':
      this.write = alignedWrite
      this.alignedBuffer = new Buffer(3)
      this.alignedBytes = 0
      break
  }
}
util.inherits(AlignedStringDecoder, StringDecoder)
 
AlignedStringDecoder.prototype.flush = function() {
  if (!this.alignedBuffer || !this.alignedBytes) return ''
  var leftover = this.alignedBuffer.toString(this.encoding, 0, this.alignedBytes)
  this.alignedBytes = 0
  return leftover
}
 
function alignedWrite(buffer) {
  var rem = (this.alignedBytes + buffer.length) % this.alignedBuffer.length
  if (!rem && !this.alignedBytes) return buffer.toString(this.encoding)
 
  var returnBuffer = new Buffer(this.alignedBytes + buffer.length - rem)
 
  this.alignedBuffer.copy(returnBuffer, 0, 0, this.alignedBytes)
  buffer.copy(returnBuffer, this.alignedBytes, 0, buffer.length - rem)
 
  buffer.copy(this.alignedBuffer, 0, buffer.length - rem, buffer.length)
  this.alignedBytes = rem
 
  return returnBuffer.toString(this.encoding)
}
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/

Statements: 20.16% (126 / 625)      Branches: 0.71% (3 / 423)      Functions: 8.96% (6 / 67)      Lines: 20.29% (126 / 621)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/
File Statements Branches Functions Lines
cookie.js 18.8% (91 / 484) 0.83% (3 / 360) 8.89% (4 / 45) 18.96% (91 / 480)
memstore.js 28.57% (18 / 63) 0% (0 / 29) 8.33% (1 / 12) 28.57% (18 / 63)
pathMatch.js 18.18% (2 / 11) 0% (0 / 8) 0% (0 / 1) 18.18% (2 / 11)
permuteDomain.js 18.75% (3 / 16) 0% (0 / 4) 0% (0 / 1) 18.75% (3 / 16)
pubsuffix.js 8.33% (3 / 36) 0% (0 / 22) 0% (0 / 1) 8.33% (3 / 36)
store.js 60% (9 / 15) 100% (0 / 0) 14.29% (1 / 7) 60% (9 / 15)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/cookie.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/cookie.js

Statements: 18.8% (91 / 484)      Branches: 0.83% (3 / 360)      Functions: 8.89% (4 / 45)      Lines: 18.96% (91 / 480)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090                                                              1 1 1 1 1 1   1 1 1         1       1 1             1       1     1   1 1 1   1       1     1       1   1 1   1       1                                                                                                                                                                                                                                                     1                     1                             1                                                                                                             1                                               1                                                                                                                                                                                                                                                                                                             1                                                                                       1                                           1                                       1                               1                     1 1   1 1     1 1 1 1 1 1 1     1 1 1 1 1 1   1 15     15   1   1                 1                                                     1               1                 1                 1                                                                                 1                                                       1                             1                       1         1                 1 1       1 1   1   1 1 1   1 1                                                                                                                                                       1                                                                     1 1                                                     1                                                                                                                                     1 1                                     1 1                                 1 4                                         1 4     1                                      
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';
var net = require('net');
var urlParse = require('url').parse;
var pubsuffix = require('./pubsuffix');
var Store = require('./store').Store;
var MemoryCookieStore = require('./memstore').MemoryCookieStore;
var pathMatch = require('./pathMatch').pathMatch;
 
var punycode;
try {
  punycode = require('punycode');
} catch(e) {
  console.warn("cookie: can't load punycode; won't use punycode for domain normalization");
}
 
var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
 
// From RFC6265 S4.1.1
// note that it excludes \x3B ";"
var COOKIE_OCTET  = /[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/;
var COOKIE_OCTETS = new RegExp('^'+COOKIE_OCTET.source+'$');
 
// Double quotes are part of the value (see: S4.1.1).
// '\r', '\n' and '\0' should be treated as a terminator in the "relaxed" mode
// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60)
// '=' and ';' are attribute/values separators
// (see: https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L64)
var COOKIE_PAIR = /^([^=;]+)\s*=\s*(("?)[^\n\r\0]*\3)/;
 
// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
// Note ';' is \x3B
var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
 
// Used for checking whether or not there is a trailing semi-colon
var TRAILING_SEMICOLON = /;+$/;
 
var DAY_OF_MONTH = /^(\d{1,2})[^\d]*$/;
var TIME = /^(\d{1,2})[^\d]*:(\d{1,2})[^\d]*:(\d{1,2})[^\d]*$/;
var MONTH = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/i;
 
var MONTH_TO_NUM = {
  jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
  jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
};
var NUM_TO_MONTH = [
  'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
];
var NUM_TO_DAY = [
  'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
];
 
var YEAR = /^(\d{2}|\d{4})$/; // 2 to 4 digits
 
var MAX_TIME = 2147483647000; // 31-bit max
var MIN_TIME = 0; // 31-bit min
 
var cookiesCreated = 0; // Number of cookies created in runtime
 
 
// RFC6265 S5.1.1 date parser:
function parseDate(str) {
  if (!str) {
    return;
  }
 
  /* RFC6265 S5.1.1:
   * 2. Process each date-token sequentially in the order the date-tokens
   * appear in the cookie-date
   */
  var tokens = str.split(DATE_DELIM);
  if (!tokens) {
    return;
  }
 
  var hour = null;
  var minutes = null;
  var seconds = null;
  var day = null;
  var month = null;
  var year = null;
 
  for (var i=0; i<tokens.length; i++) {
    var token = tokens[i].trim();
    if (!token.length) {
      continue;
    }
 
    var result;
 
    /* 2.1. If the found-time flag is not set and the token matches the time
     * production, set the found-time flag and set the hour- value,
     * minute-value, and second-value to the numbers denoted by the digits in
     * the date-token, respectively.  Skip the remaining sub-steps and continue
     * to the next date-token.
     */
    if (seconds === null) {
      result = TIME.exec(token);
      if (result) {
        hour = parseInt(result[1], 10);
        minutes = parseInt(result[2], 10);
        seconds = parseInt(result[3], 10);
        /* RFC6265 S5.1.1.5:
         * [fail if]
         * *  the hour-value is greater than 23,
         * *  the minute-value is greater than 59, or
         * *  the second-value is greater than 59.
         */
        if(hour > 23 || minutes > 59 || seconds > 59) {
          return;
        }
 
        continue;
      }
    }
 
    /* 2.2. If the found-day-of-month flag is not set and the date-token matches
     * the day-of-month production, set the found-day-of- month flag and set
     * the day-of-month-value to the number denoted by the date-token.  Skip
     * the remaining sub-steps and continue to the next date-token.
     */
    if (day === null) {
      result = DAY_OF_MONTH.exec(token);
      if (result) {
        day = parseInt(result, 10);
        /* RFC6265 S5.1.1.5:
         * [fail if] the day-of-month-value is less than 1 or greater than 31
         */
        if(day < 1 || day > 31) {
          return;
        }
        continue;
      }
    }
 
    /* 2.3. If the found-month flag is not set and the date-token matches the
     * month production, set the found-month flag and set the month-value to
     * the month denoted by the date-token.  Skip the remaining sub-steps and
     * continue to the next date-token.
     */
    if (month === null) {
      result = MONTH.exec(token);
      if (result) {
        month = MONTH_TO_NUM[result[1].toLowerCase()];
        continue;
      }
    }
 
    /* 2.4. If the found-year flag is not set and the date-token matches the year
     * production, set the found-year flag and set the year-value to the number
     * denoted by the date-token.  Skip the remaining sub-steps and continue to
     * the next date-token.
     */
    if (year === null) {
      result = YEAR.exec(token);
      if (result) {
        year = parseInt(result[0], 10);
        /* From S5.1.1:
         * 3.  If the year-value is greater than or equal to 70 and less
         * than or equal to 99, increment the year-value by 1900.
         * 4.  If the year-value is greater than or equal to 0 and less
         * than or equal to 69, increment the year-value by 2000.
         */
        if (70 <= year && year <= 99) {
          year += 1900;
        } else if (0 <= year && year <= 69) {
          year += 2000;
        }
 
        if (year < 1601) {
          return; // 5. ... the year-value is less than 1601
        }
      }
    }
  }
 
  if (seconds === null || day === null || month === null || year === null) {
    return; // 5. ... at least one of the found-day-of-month, found-month, found-
            // year, or found-time flags is not set,
  }
 
  return new Date(Date.UTC(year, month, day, hour, minutes, seconds));
}
 
function formatDate(date) {
  var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
  var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
  var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
  var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
  return NUM_TO_DAY[date.getUTCDay()] + ', ' +
    d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
    h+':'+m+':'+s+' GMT';
}
 
// S5.1.2 Canonicalized Host Names
function canonicalDomain(str) {
  if (str == null) {
    return null;
  }
  str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
 
  // convert to IDN if any non-ASCII characters
  if (punycode && /[^\u0001-\u007f]/.test(str)) {
    str = punycode.toASCII(str);
  }
 
  return str.toLowerCase();
}
 
// S5.1.3 Domain Matching
function domainMatch(str, domStr, canonicalize) {
  if (str == null || domStr == null) {
    return null;
  }
  if (canonicalize !== false) {
    str = canonicalDomain(str);
    domStr = canonicalDomain(domStr);
  }
 
  /*
   * "The domain string and the string are identical. (Note that both the
   * domain string and the string will have been canonicalized to lower case at
   * this point)"
   */
  if (str == domStr) {
    return true;
  }
 
  /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
 
  /* "* The string is a host name (i.e., not an IP address)." */
  if (net.isIP(str)) {
    return false;
  }
 
  /* "* The domain string is a suffix of the string" */
  var idx = str.indexOf(domStr);
  if (idx <= 0) {
    return false; // it's a non-match (-1) or prefix (0)
  }
 
  // e.g "a.b.c".indexOf("b.c") === 2
  // 5 === 3+2
  if (str.length !== domStr.length + idx) { // it's not a suffix
    return false;
  }
 
  /* "* The last character of the string that is not included in the domain
  * string is a %x2E (".") character." */
  if (str.substr(idx-1,1) !== '.') {
    return false;
  }
 
  return true;
}
 
 
// RFC6265 S5.1.4 Paths and Path-Match
 
/*
 * "The user agent MUST use an algorithm equivalent to the following algorithm
 * to compute the default-path of a cookie:"
 *
 * Assumption: the path (and not query part or absolute uri) is passed in.
 */
function defaultPath(path) {
  // "2. If the uri-path is empty or if the first character of the uri-path is not
  // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
  if (!path || path.substr(0,1) !== "/") {
    return "/";
  }
 
  // "3. If the uri-path contains no more than one %x2F ("/") character, output
  // %x2F ("/") and skip the remaining step."
  if (path === "/") {
    return path;
  }
 
  var rightSlash = path.lastIndexOf("/");
  if (rightSlash === 0) {
    return "/";
  }
 
  // "4. Output the characters of the uri-path from the first character up to,
  // but not including, the right-most %x2F ("/")."
  return path.slice(0, rightSlash);
}
 
 
function parse(str) {
  str = str.trim();
 
  // S4.1.1 Trailing semi-colons are not part of the specification.
  var semiColonCheck = TRAILING_SEMICOLON.exec(str);
  if (semiColonCheck) {
    str = str.slice(0, semiColonCheck.index);
  }
 
  // We use a regex to parse the "name-value-pair" part of S5.2
  var firstSemi = str.indexOf(';'); // S5.2 step 1
  var result = COOKIE_PAIR.exec(firstSemi === -1 ? str : str.substr(0,firstSemi));
 
  // Rx satisfies the "the name string is empty" and "lacks a %x3D ("=")"
  // constraints as well as trimming any whitespace.
  if (!result) {
    return;
  }
 
  var c = new Cookie();
  c.key = result[1].trim();
  c.value = result[2].trim();
 
  if (firstSemi === -1) {
    return c;
  }
 
  // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
  // (including the %x3B (";") in question)." plus later on in the same section
  // "discard the first ";" and trim".
  var unparsed = str.slice(firstSemi).replace(/^\s*;\s*/,'').trim();
 
  // "If the unparsed-attributes string is empty, skip the rest of these
  // steps."
  if (unparsed.length === 0) {
    return c;
  }
 
  /*
   * S5.2 says that when looping over the items "[p]rocess the attribute-name
   * and attribute-value according to the requirements in the following
   * subsections" for every item.  Plus, for many of the individual attributes
   * in S5.3 it says to use the "attribute-value of the last attribute in the
   * cookie-attribute-list".  Therefore, in this implementation, we overwrite
   * the previous value.
   */
  var cookie_avs = unparsed.split(/\s*;\s*/);
  while (cookie_avs.length) {
    var av = cookie_avs.shift();
    var av_sep = av.indexOf('=');
    var av_key, av_value;
 
    if (av_sep === -1) {
      av_key = av;
      av_value = null;
    } else {
      av_key = av.substr(0,av_sep);
      av_value = av.substr(av_sep+1);
    }
 
    av_key = av_key.trim().toLowerCase();
 
    if (av_value) {
      av_value = av_value.trim();
    }
 
    switch(av_key) {
    case 'expires': // S5.2.1
      if (av_value) {
        var exp = parseDate(av_value);
        // "If the attribute-value failed to parse as a cookie date, ignore the
        // cookie-av."
        if (exp) {
          // over and underflow not realistically a concern: V8's getTime() seems to
          // store something larger than a 32-bit time_t (even with 32-bit node)
          c.expires = exp;
        }
      }
      break;
 
    case 'max-age': // S5.2.2
      if (av_value) {
        // "If the first character of the attribute-value is not a DIGIT or a "-"
        // character ...[or]... If the remainder of attribute-value contains a
        // non-DIGIT character, ignore the cookie-av."
        if (/^-?[0-9]+$/.test(av_value)) {
          var delta = parseInt(av_value, 10);
          // "If delta-seconds is less than or equal to zero (0), let expiry-time
          // be the earliest representable date and time."
          c.setMaxAge(delta);
        }
      }
      break;
 
    case 'domain': // S5.2.3
      // "If the attribute-value is empty, the behavior is undefined.  However,
      // the user agent SHOULD ignore the cookie-av entirely."
      if (av_value) {
        // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
        // (".") character."
        var domain = av_value.trim().replace(/^\./, '');
        if (domain) {
          // "Convert the cookie-domain to lower case."
          c.domain = domain.toLowerCase();
        }
      }
      break;
 
    case 'path': // S5.2.4
      /*
       * "If the attribute-value is empty or if the first character of the
       * attribute-value is not %x2F ("/"):
       *   Let cookie-path be the default-path.
       * Otherwise:
       *   Let cookie-path be the attribute-value."
       *
       * We'll represent the default-path as null since it depends on the
       * context of the parsing.
       */
      c.path = av_value && av_value[0] === "/" ? av_value : null;
      break;
 
    case 'secure': // S5.2.5
      /*
       * "If the attribute-name case-insensitively matches the string "Secure",
       * the user agent MUST append an attribute to the cookie-attribute-list
       * with an attribute-name of Secure and an empty attribute-value."
       */
      c.secure = true;
      break;
 
    case 'httponly': // S5.2.6 -- effectively the same as 'secure'
      c.httpOnly = true;
      break;
 
    default:
      c.extensions = c.extensions || [];
      c.extensions.push(av);
      break;
    }
  }
 
  // ensure a default date for sorting:
  c.creation = new Date();
  //NOTE: add runtime index for the cookieCompare() to resolve the situation when Date's precision is not enough .
  //Store initial UTC time as well, so we will be able to determine if we need to fallback to the Date object.
  c._creationRuntimeIdx = ++cookiesCreated;
  c._initialCreationTime = c.creation.getTime();
  return c;
}
 
function fromJSON(str) {
  if (!str) {
    return null;
  }
 
  var obj;
  try {
    obj = JSON.parse(str);
  } catch (e) {
    return null;
  }
 
  var c = new Cookie();
  for (var i=0; i<numCookieProperties; i++) {
    var prop = cookieProperties[i];
    if (obj[prop] == null) {
      continue;
    }
    if (prop === 'expires' ||
        prop === 'creation' ||
        prop === 'lastAccessed')
    {
      c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]);
    } else {
      c[prop] = obj[prop];
    }
  }
 
 
  // ensure a default date for sorting:
  c.creation = c.creation || new Date();
 
  return c;
}
 
/* Section 5.4 part 2:
 * "*  Cookies with longer paths are listed before cookies with
 *     shorter paths.
 *
 *  *  Among cookies that have equal-length path fields, cookies with
 *     earlier creation-times are listed before cookies with later
 *     creation-times."
 */
 
function cookieCompare(a,b) {
  // descending for length: b CMP a
  var deltaLen = (b.path ? b.path.length : 0) - (a.path ? a.path.length : 0);
  if (deltaLen !== 0) {
    return deltaLen;
  }
 
  var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
  var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
 
  // NOTE: if creation dates are equal and they were not modified from the outside,
  // then use _creationRuntimeIdx for the comparison.
  if(aTime === bTime && aTime === a._initialCreationTime && bTime === b._initialCreationTime) {
    return a._creationRuntimeIdx - b._creationRuntimeIdx;
  }
 
  // ascending for time: a CMP b
  return aTime - bTime;
}
 
// Gives the permutation of all possible pathMatch()es of a given path. The
// array is in longest-to-shortest order.  Handy for indexing.
function permutePath(path) {
  if (path === '/') {
    return ['/'];
  }
  if (path.lastIndexOf('/') === path.length-1) {
    path = path.substr(0,path.length-1);
  }
  var permutations = [path];
  while (path.length > 1) {
    var lindex = path.lastIndexOf('/');
    if (lindex === 0) {
      break;
    }
    path = path.substr(0,lindex);
    permutations.push(path);
  }
  permutations.push('/');
  return permutations;
}
 
function getCookieContext(url) {
  if (url instanceof Object) {
    return url;
  }
  // NOTE: decodeURI will throw on malformed URIs (see GH-32).
  // Therefore, we will just skip decoding for such URIs.
  try {
    url = decodeURI(url);
  }
  catch(err) {
    // Silently swallow error
  }
 
  return urlParse(url);
}
 
function Cookie (opts) {
  if (typeof opts !== "object") {
    return;
  }
  Object.keys(opts).forEach(function (key) {
    if (Cookie.prototype.hasOwnProperty(key)) {
      this[key] = opts[key] || Cookie.prototype[key];
    }
  }.bind(this));
}
 
Cookie.parse = parse;
Cookie.fromJSON = fromJSON;
 
Cookie.prototype.key = "";
Cookie.prototype.value = "";
 
// the order in which the RFC has them:
Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
Cookie.prototype.domain = null;
Cookie.prototype.path = null;
Cookie.prototype.secure = false;
Cookie.prototype.httpOnly = false;
Cookie.prototype.extensions = null;
 
// set by the CookieJar:
Cookie.prototype.hostOnly = null; // boolean when set
Cookie.prototype.pathIsDefault = null; // boolean when set
Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
Cookie.prototype._initialCreationTime = null; // Used to determine if cookie.creation was modified
Cookie.prototype._creationRuntimeIdx = null; // Runtime index of the created cookie, used in cookieCompare()
Cookie.prototype.lastAccessed = null; // Date when set
 
var cookieProperties = Object.freeze(Object.keys(Cookie.prototype).map(function(p) {
  Iif (p instanceof Function) {
    return;
  }
  return p;
}));
var numCookieProperties = cookieProperties.length;
 
Cookie.prototype.inspect = function inspect() {
  var now = Date.now();
  return 'Cookie="'+this.toString() +
    '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
    '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
    '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
    '"';
};
 
Cookie.prototype.validate = function validate() {
  if (!COOKIE_OCTETS.test(this.value)) {
    return false;
  }
  if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
    return false;
  }
  if (this.maxAge != null && this.maxAge <= 0) {
    return false; // "Max-Age=" non-zero-digit *DIGIT
  }
  if (this.path != null && !PATH_VALUE.test(this.path)) {
    return false;
  }
 
  var cdomain = this.cdomain();
  if (cdomain) {
    if (cdomain.match(/\.$/)) {
      return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
    }
    var suffix = pubsuffix.getPublicSuffix(cdomain);
    if (suffix == null) { // it's a public suffix
      return false;
    }
  }
  return true;
};
 
Cookie.prototype.setExpires = function setExpires(exp) {
  if (exp instanceof Date) {
    this.expires = exp;
  } else {
    this.expires = parseDate(exp) || "Infinity";
  }
};
 
Cookie.prototype.setMaxAge = function setMaxAge(age) {
  if (age === Infinity || age === -Infinity) {
    this.maxAge = age.toString(); // so JSON.stringify() works
  } else {
    this.maxAge = age;
  }
};
 
// gives Cookie header format
Cookie.prototype.cookieString = function cookieString() {
  var val = this.value;
  if (val == null) {
    val = '';
  }
  return this.key+'='+val;
};
 
// gives Set-Cookie header format
Cookie.prototype.toString = function toString() {
  var str = this.cookieString();
 
  if (this.expires != Infinity) {
    if (this.expires instanceof Date) {
      str += '; Expires='+formatDate(this.expires);
    } else {
      str += '; Expires='+this.expires;
    }
  }
 
  if (this.maxAge != null && this.maxAge != Infinity) {
    str += '; Max-Age='+this.maxAge;
  }
 
  if (this.domain && !this.hostOnly) {
    str += '; Domain='+this.domain;
  }
  if (this.path) {
    str += '; Path='+this.path;
  }
 
  if (this.secure) {
    str += '; Secure';
  }
  if (this.httpOnly) {
    str += '; HttpOnly';
  }
  if (this.extensions) {
    this.extensions.forEach(function(ext) {
      str += '; '+ext;
    });
  }
 
  return str;
};
 
// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere)
// S5.3 says to give the "latest representable date" for which we use Infinity
// For "expired" we use 0
Cookie.prototype.TTL = function TTL(now) {
  /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
   * attribute, the Max-Age attribute has precedence and controls the
   * expiration date of the cookie.
   * (Concurs with S5.3 step 3)
   */
  if (this.maxAge != null) {
    return this.maxAge<=0 ? 0 : this.maxAge*1000;
  }
 
  var expires = this.expires;
  if (expires != Infinity) {
    if (!(expires instanceof Date)) {
      expires = parseDate(expires) || Infinity;
    }
 
    if (expires == Infinity) {
      return Infinity;
    }
 
    return expires.getTime() - (now || Date.now());
  }
 
  return Infinity;
};
 
// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere)
Cookie.prototype.expiryTime = function expiryTime(now) {
  if (this.maxAge != null) {
    var relativeTo = this.creation || now || new Date();
    var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
    return relativeTo.getTime() + age;
  }
 
  if (this.expires == Infinity) {
    return Infinity;
  }
  return this.expires.getTime();
};
 
// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
// elsewhere), except it returns a Date
Cookie.prototype.expiryDate = function expiryDate(now) {
  var millisec = this.expiryTime(now);
  if (millisec == Infinity) {
    return new Date(MAX_TIME);
  } else if (millisec == -Infinity) {
    return new Date(MIN_TIME);
  } else {
    return new Date(millisec);
  }
};
 
// This replaces the "persistent-flag" parts of S5.3 step 3
Cookie.prototype.isPersistent = function isPersistent() {
  return (this.maxAge != null || this.expires != Infinity);
};
 
// Mostly S5.1.2 and S5.2.3:
Cookie.prototype.cdomain =
Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
  if (this.domain == null) {
    return null;
  }
  return canonicalDomain(this.domain);
};
 
 
function CookieJar(store, rejectPublicSuffixes) {
  Iif (rejectPublicSuffixes != null) {
    this.rejectPublicSuffixes = rejectPublicSuffixes;
  }
 
  Eif (!store) {
    store = new MemoryCookieStore();
  }
  this.store = store;
}
CookieJar.prototype.store = null;
CookieJar.prototype.rejectPublicSuffixes = true;
var CAN_BE_SYNC = [];
 
CAN_BE_SYNC.push('setCookie');
CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
  var err;
  var context = getCookieContext(url);
  if (options instanceof Function) {
    cb = options;
    options = {};
  }
 
  var host = canonicalDomain(context.hostname);
 
  // S5.3 step 1
  if (!(cookie instanceof Cookie)) {
    cookie = Cookie.parse(cookie);
  }
  if (!cookie) {
    err = new Error("Cookie failed to parse");
    return cb(options.ignoreError ? null : err);
  }
 
  // S5.3 step 2
  var now = options.now || new Date(); // will assign later to save effort in the face of errors
 
  // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
 
  // S5.3 step 4: NOOP; domain is null by default
 
  // S5.3 step 5: public suffixes
  if (this.rejectPublicSuffixes && cookie.domain) {
    var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
    if (suffix == null) { // e.g. "com"
      err = new Error("Cookie has domain set to a public suffix");
      return cb(options.ignoreError ? null : err);
    }
  }
 
  // S5.3 step 6:
  if (cookie.domain) {
    if (!domainMatch(host, cookie.cdomain(), false)) {
      err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
      return cb(options.ignoreError ? null : err);
    }
 
    if (cookie.hostOnly == null) { // don't reset if already set
      cookie.hostOnly = false;
    }
 
  } else {
    cookie.hostOnly = true;
    cookie.domain = host;
  }
 
  //S5.2.4 If the attribute-value is empty or if the first character of the
  //attribute-value is not %x2F ("/"):
  //Let cookie-path be the default-path.
  if (!cookie.path || cookie.path[0] !== '/') {
    cookie.path = defaultPath(context.pathname);
    cookie.pathIsDefault = true;
  }
 
  // S5.3 step 8: NOOP; secure attribute
  // S5.3 step 9: NOOP; httpOnly attribute
 
  // S5.3 step 10
  if (options.http === false && cookie.httpOnly) {
    err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
    return cb(options.ignoreError ? null : err);
  }
 
  var store = this.store;
 
  if (!store.updateCookie) {
    store.updateCookie = function(oldCookie, newCookie, cb) {
      this.putCookie(newCookie, cb);
    };
  }
 
  function withCookie(err, oldCookie) {
    if (err) {
      return cb(err);
    }
 
    var next = function(err) {
      if (err) {
        return cb(err);
      } else {
        cb(null, cookie);
      }
    };
 
    if (oldCookie) {
      // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
      // domain, and path as the newly created cookie:"
      if (options.http === false && oldCookie.httpOnly) { // step 11.2
        err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
        return cb(options.ignoreError ? null : err);
      }
      cookie.creation = oldCookie.creation; // step 11.3
      cookie.lastAccessed = now;
      // Step 11.4 (delete cookie) is implied by just setting the new one:
      store.updateCookie(oldCookie, cookie, next); // step 12
 
    } else {
      cookie.creation = cookie.lastAccessed = now;
      store.putCookie(cookie, next); // step 12
    }
  }
 
  store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
};
 
// RFC6365 S5.4
CAN_BE_SYNC.push('getCookies');
CookieJar.prototype.getCookies = function(url, options, cb) {
  var context = getCookieContext(url);
  if (options instanceof Function) {
    cb = options;
    options = {};
  }
 
  var host = canonicalDomain(context.hostname);
  var path = context.pathname || '/';
 
  var secure = options.secure;
  if (secure == null && context.protocol &&
      (context.protocol == 'https:' || context.protocol == 'wss:'))
  {
    secure = true;
  }
 
  var http = options.http;
  if (http == null) {
    http = true;
  }
 
  var now = options.now || Date.now();
  var expireCheck = options.expire !== false;
  var allPaths = !!options.allPaths;
  var store = this.store;
 
  function matchingCookie(c) {
    // "Either:
    //   The cookie's host-only-flag is true and the canonicalized
    //   request-host is identical to the cookie's domain.
    // Or:
    //   The cookie's host-only-flag is false and the canonicalized
    //   request-host domain-matches the cookie's domain."
    if (c.hostOnly) {
      if (c.domain != host) {
        return false;
      }
    } else {
      if (!domainMatch(host, c.domain, false)) {
        return false;
      }
    }
 
    // "The request-uri's path path-matches the cookie's path."
    if (!allPaths && !pathMatch(path, c.path)) {
      return false;
    }
 
    // "If the cookie's secure-only-flag is true, then the request-uri's
    // scheme must denote a "secure" protocol"
    if (c.secure && !secure) {
      return false;
    }
 
    // "If the cookie's http-only-flag is true, then exclude the cookie if the
    // cookie-string is being generated for a "non-HTTP" API"
    if (c.httpOnly && !http) {
      return false;
    }
 
    // deferred from S5.3
    // non-RFC: allow retention of expired cookies by choice
    if (expireCheck && c.expiryTime() <= now) {
      store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
      return false;
    }
 
    return true;
  }
 
  store.findCookies(host, allPaths ? null : path, function(err,cookies) {
    if (err) {
      return cb(err);
    }
 
    cookies = cookies.filter(matchingCookie);
 
    // sorting of S5.4 part 2
    if (options.sort !== false) {
      cookies = cookies.sort(cookieCompare);
    }
 
    // S5.4 part 3
    var now = new Date();
    cookies.forEach(function(c) {
      c.lastAccessed = now;
    });
    // TODO persist lastAccessed
 
    cb(null,cookies);
  });
};
 
CAN_BE_SYNC.push('getCookieString');
CookieJar.prototype.getCookieString = function(/*..., cb*/) {
  var args = Array.prototype.slice.call(arguments,0);
  var cb = args.pop();
  var next = function(err,cookies) {
    if (err) {
      cb(err);
    } else {
      cb(null, cookies
        .sort(cookieCompare)
        .map(function(c){
          return c.cookieString();
        })
        .join('; '));
    }
  };
  args.push(next);
  this.getCookies.apply(this,args);
};
 
CAN_BE_SYNC.push('getSetCookieStrings');
CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
  var args = Array.prototype.slice.call(arguments,0);
  var cb = args.pop();
  var next = function(err,cookies) {
    if (err) {
      cb(err);
    } else {
      cb(null, cookies.map(function(c){
        return c.toString();
      }));
    }
  };
  args.push(next);
  this.getCookies.apply(this,args);
};
 
// Use a closure to provide a true imperative API for synchronous stores.
function syncWrap(method) {
  return function() {
    if (!this.store.synchronous) {
      throw new Error('CookieJar store is not synchronous; use async API instead.');
    }
 
    var args = Array.prototype.slice.call(arguments);
    var syncErr, syncResult;
    args.push(function syncCb(err, result) {
      syncErr = err;
      syncResult = result;
    });
    this[method].apply(this, args);
 
    if (syncErr) {
      throw syncErr;
    }
    return syncResult;
  };
}
 
// wrap all declared CAN_BE_SYNC methods in the sync wrapper
CAN_BE_SYNC.forEach(function(method) {
  CookieJar.prototype[method+'Sync'] = syncWrap(method);
});
 
module.exports = {
  CookieJar: CookieJar,
  Cookie: Cookie,
  Store: Store,
  MemoryCookieStore: MemoryCookieStore,
  parseDate: parseDate,
  formatDate: formatDate,
  parse: parse,
  fromJSON: fromJSON,
  domainMatch: domainMatch,
  defaultPath: defaultPath,
  pathMatch: pathMatch,
  getPublicSuffix: pubsuffix.getPublicSuffix,
  cookieCompare: cookieCompare,
  permuteDomain: require('./permuteDomain').permuteDomain,
  permutePath: permutePath,
  canonicalDomain: canonicalDomain
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/memstore.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/memstore.js

Statements: 28.57% (18 / 63)      Branches: 0% (0 / 29)      Functions: 8.33% (1 / 12)      Lines: 28.57% (18 / 63)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144                                                              1 1 1 1   1 1 1   1 1 1 1     1       1                   1                                                                                             1                     1             1             1                      
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';
var Store = require('./store').Store;
var permuteDomain = require('./permuteDomain').permuteDomain;
var pathMatch = require('./pathMatch').pathMatch;
var util = require('util');
 
function MemoryCookieStore() {
  Store.call(this);
  this.idx = {};
}
util.inherits(MemoryCookieStore, Store);
exports.MemoryCookieStore = MemoryCookieStore;
MemoryCookieStore.prototype.idx = null;
MemoryCookieStore.prototype.synchronous = true;
 
// force a default depth:
MemoryCookieStore.prototype.inspect = function() {
  return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
};
 
MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
  if (!this.idx[domain]) {
    return cb(null,undefined);
  }
  if (!this.idx[domain][path]) {
    return cb(null,undefined);
  }
  return cb(null,this.idx[domain][path][key]||null);
};
 
MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
  var results = [];
  if (!domain) {
    return cb(null,[]);
  }
 
  var pathMatcher;
  if (!path) {
    // null means "all paths"
    pathMatcher = function matchAll(domainIndex) {
      for (var curPath in domainIndex) {
        var pathIndex = domainIndex[curPath];
        for (var key in pathIndex) {
          results.push(pathIndex[key]);
        }
      }
    };
 
  } else {
    pathMatcher = function matchRFC(domainIndex) {
       //NOTE: we should use path-match algorithm from S5.1.4 here
       //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
       Object.keys(domainIndex).forEach(function (cookiePath) {
         if (pathMatch(path, cookiePath)) {
           var pathIndex = domainIndex[cookiePath];
 
           for (var key in pathIndex) {
             results.push(pathIndex[key]);
           }
         }
       });
     };
  }
 
  var domains = permuteDomain(domain) || [domain];
  var idx = this.idx;
  domains.forEach(function(curDomain) {
    var domainIndex = idx[curDomain];
    if (!domainIndex) {
      return;
    }
    pathMatcher(domainIndex);
  });
 
  cb(null,results);
};
 
MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
  if (!this.idx[cookie.domain]) {
    this.idx[cookie.domain] = {};
  }
  if (!this.idx[cookie.domain][cookie.path]) {
    this.idx[cookie.domain][cookie.path] = {};
  }
  this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
  cb(null);
};
 
MemoryCookieStore.prototype.updateCookie = function updateCookie(oldCookie, newCookie, cb) {
  // updateCookie() may avoid updating cookies that are identical.  For example,
  // lastAccessed may not be important to some stores and an equality
  // comparison could exclude that field.
  this.putCookie(newCookie,cb);
};
 
MemoryCookieStore.prototype.removeCookie = function removeCookie(domain, path, key, cb) {
  if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
    delete this.idx[domain][path][key];
  }
  cb(null);
};
 
MemoryCookieStore.prototype.removeCookies = function removeCookies(domain, path, cb) {
  if (this.idx[domain]) {
    if (path) {
      delete this.idx[domain][path];
    } else {
      delete this.idx[domain];
    }
  }
  return cb(null);
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/pathMatch.js

Statements: 18.18% (2 / 11)      Branches: 0% (0 / 8)      Functions: 0% (0 / 1)      Lines: 18.18% (2 / 11)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                                                      1                                                 1    
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";
/*
 * "A request-path path-matches a given cookie-path if at least one of the
 * following conditions holds:"
 */
function pathMatch (reqPath, cookiePath) {
  // "o  The cookie-path and the request-path are identical."
  if (cookiePath === reqPath) {
    return true;
  }
 
  var idx = reqPath.indexOf(cookiePath);
  if (idx === 0) {
    // "o  The cookie-path is a prefix of the request-path, and the last
    // character of the cookie-path is %x2F ("/")."
    if (cookiePath.substr(-1) === "/") {
      return true;
    }
 
    // " o  The cookie-path is a prefix of the request-path, and the first
    // character of the request-path that is not included in the cookie- path
    // is a %x2F ("/") character."
    if (reqPath.substr(cookiePath.length, 1) === "/") {
      return true;
    }
  }
 
  return false;
}
 
exports.pathMatch = pathMatch;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/permuteDomain.js

Statements: 18.75% (3 / 16)      Branches: 0% (0 / 4)      Functions: 0% (0 / 1)      Lines: 18.75% (3 / 16)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                                              1       1                                       1    
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";
var pubsuffix = require('./pubsuffix');
 
// Gives the permutation of all possible domainMatch()es of a given domain. The
// array is in shortest-to-longest order.  Handy for indexing.
function permuteDomain (domain) {
  var pubSuf = pubsuffix.getPublicSuffix(domain);
  if (!pubSuf) {
    return null;
  }
  if (pubSuf == domain) {
    return [domain];
  }
 
  var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
  var parts = prefix.split('.').reverse();
  var cur = pubSuf;
  var permutations = [cur];
  while (parts.length) {
    cur = parts.shift() + '.' + cur;
    permutations.push(cur);
  }
  return permutations;
}
 
exports.permuteDomain = permuteDomain;
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/pubsuffix.js

Statements: 8.33% (3 / 36)      Branches: 0% (0 / 22)      Functions: 0% (0 / 1)      Lines: 8.33% (3 / 36)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100              1   1                                                                                                                                                                         1          
/****************************************************
 * AUTOMATICALLY GENERATED by generate-pubsuffix.js *
 *                  DO NOT EDIT!                    *
 ****************************************************/
 
"use strict";
 
var punycode = require('punycode');
 
module.exports.getPublicSuffix = function getPublicSuffix(domain) {
  /*!
   * Copyright (c) 2015, Salesforce.com, Inc.
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice,
   * this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   * this list of conditions and the following disclaimer in the documentation
   * and/or other materials provided with the distribution.
   *
   * 3. Neither the name of Salesforce.com nor the names of its contributors may
   * be used to endorse or promote products derived from this software without
   * specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   * POSSIBILITY OF SUCH DAMAGE.
   */
  if (!domain) {
    return null;
  }
  if (domain.match(/^\./)) {
    return null;
  }
  var asciiDomain = punycode.toASCII(domain);
  var converted = false;
  if (asciiDomain !== domain) {
    domain = asciiDomain;
    converted = true;
  }
  if (index[domain]) {
    return null;
  }
 
  domain = domain.toLowerCase();
  var parts = domain.split('.').reverse();
 
  var suffix = '';
  var suffixLen = 0;
  for (var i=0; i<parts.length; i++) {
    var part = parts[i];
    var starstr = '*'+suffix;
    var partstr = part+suffix;
 
    if (index[starstr]) { // star rule matches
      suffixLen = i+1;
      if (index[partstr] === false) { // exception rule matches (NB: false, not undefined)
        suffixLen--;
      }
    } else if (index[partstr]) { // exact match, not exception
      suffixLen = i+1;
    }
 
    suffix = '.'+partstr;
  }
 
  if (index['*'+suffix]) { // *.domain exists (e.g. *.kyoto.jp for domain='kyoto.jp');
    return null;
  }
 
  suffixLen = suffixLen || 1;
  if (parts.length > suffixLen) {
    var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.');
    return converted ? punycode.toUnicode(publicSuffix) : publicSuffix;
  }
 
  return null;
};
 
// The following generated structure is used under the MPL version 1.1
// See public-suffix.txt for more information
 
var index = module.exports.index = Object.freeze(
{"ac":true,"com.ac":true,"edu.ac":true,"gov.ac":true,"net.ac":true,"mil.ac":true,"org.ac":true,"ad":true,"nom.ad":true,"ae":true,"co.ae":true,"net.ae":true,"org.ae":true,"sch.ae":true,"ac.ae":true,"gov.ae":true,"mil.ae":true,"aero":true,"accident-investigation.aero":true,"accident-prevention.aero":true,"aerobatic.aero":true,"aeroclub.aero":true,"aerodrome.aero":true,"agents.aero":true,"aircraft.aero":true,"airline.aero":true,"airport.aero":true,"air-surveillance.aero":true,"airtraffic.aero":true,"air-traffic-control.aero":true,"ambulance.aero":true,"amusement.aero":true,"association.aero":true,"author.aero":true,"ballooning.aero":true,"broker.aero":true,"caa.aero":true,"cargo.aero":true,"catering.aero":true,"certification.aero":true,"championship.aero":true,"charter.aero":true,"civilaviation.aero":true,"club.aero":true,"conference.aero":true,"consultant.aero":true,"consulting.aero":true,"control.aero":true,"council.aero":true,"crew.aero":true,"design.aero":true,"dgca.aero":true,"educator.aero":true,"emergency.aero":true,"engine.aero":true,"engineer.aero":true,"entertainment.aero":true,"equipment.aero":true,"exchange.aero":true,"express.aero":true,"federation.aero":true,"flight.aero":true,"freight.aero":true,"fuel.aero":true,"gliding.aero":true,"government.aero":true,"groundhandling.aero":true,"group.aero":true,"hanggliding.aero":true,"homebuilt.aero":true,"insurance.aero":true,"journal.aero":true,"journalist.aero":true,"leasing.aero":true,"logistics.aero":true,"magazine.aero":true,"maintenance.aero":true,"marketplace.aero":true,"media.aero":true,"microlight.aero":true,"modelling.aero":true,"navigation.aero":true,"parachuting.aero":true,"paragliding.aero":true,"passenger-association.aero":true,"pilot.aero":true,"press.aero":true,"production.aero":true,"recreation.aero":true,"repbody.aero":true,"res.aero":true,"research.aero":true,"rotorcraft.aero":true,"safety.aero":true,"scientist.aero":true,"services.aero":true,"show.aero":true,"skydiving.aero":true,"software.aero":true,"student.aero":true,"taxi.aero":true,"trader.aero":true,"trading.aero":true,"trainer.aero":true,"union.aero":true,"workinggroup.aero":true,"works.aero":true,"af":true,"gov.af":true,"com.af":true,"org.af":true,"net.af":true,"edu.af":true,"ag":true,"com.ag":true,"org.ag":true,"net.ag":true,"co.ag":true,"nom.ag":true,"ai":true,"off.ai":true,"com.ai":true,"net.ai":true,"org.ai":true,"al":true,"com.al":true,"edu.al":true,"gov.al":true,"mil.al":true,"net.al":true,"org.al":true,"am":true,"an":true,"com.an":true,"net.an":true,"org.an":true,"edu.an":true,"ao":true,"ed.ao":true,"gv.ao":true,"og.ao":true,"co.ao":true,"pb.ao":true,"it.ao":true,"aq":true,"ar":true,"com.ar":true,"edu.ar":true,"gob.ar":true,"gov.ar":true,"int.ar":true,"mil.ar":true,"net.ar":true,"org.ar":true,"tur.ar":true,"arpa":true,"e164.arpa":true,"in-addr.arpa":true,"ip6.arpa":true,"iris.arpa":true,"uri.arpa":true,"urn.arpa":true,"as":true,"gov.as":true,"asia":true,"at":true,"ac.at":true,"co.at":true,"gv.at":true,"or.at":true,"au":true,"com.au":true,"net.au":true,"org.au":true,"edu.au":true,"gov.au":true,"asn.au":true,"id.au":true,"info.au":true,"conf.au":true,"oz.au":true,"act.au":true,"nsw.au":true,"nt.au":true,"qld.au":true,"sa.au":true,"tas.au":true,"vic.au":true,"wa.au":true,"act.edu.au":true,"nsw.edu.au":true,"nt.edu.au":true,"qld.edu.au":true,"sa.edu.au":true,"tas.edu.au":true,"vic.edu.au":true,"wa.edu.au":true,"qld.gov.au":true,"sa.gov.au":true,"tas.gov.au":true,"vic.gov.au":true,"wa.gov.au":true,"aw":true,"com.aw":true,"ax":true,"az":true,"com.az":true,"net.az":true,"int.az":true,"gov.az":true,"org.az":true,"edu.az":true,"info.az":true,"pp.az":true,"mil.az":true,"name.az":true,"pro.az":true,"biz.az":true,"ba":true,"org.ba":true,"net.ba":true,"edu.ba":true,"gov.ba":true,"mil.ba":true,"unsa.ba":true,"unbi.ba":true,"co.ba":true,"com.ba":true,"rs.ba":true,"bb":true,"biz.bb":true,"co.bb":true,"com.bb":true,"edu.bb":true,"gov.bb":true,"info.bb":true,"net.bb":true,"org.bb":true,"store.bb":true,"tv.bb":true,"*.bd":true,"be":true,"ac.be":true,"bf":true,"gov.bf":true,"bg":true,"a.bg":true,"b.bg":true,"c.bg":true,"d.bg":true,"e.bg":true,"f.bg":true,"g.bg":true,"h.bg":true,"i.bg":true,"j.bg":true,"k.bg":true,"l.bg":true,"m.bg":true,"n.bg":true,"o.bg":true,"p.bg":true,"q.bg":true,"r.bg":true,"s.bg":true,"t.bg":true,"u.bg":true,"v.bg":true,"w.bg":true,"x.bg":true,"y.bg":true,"z.bg":true,"0.bg":true,"1.bg":true,"2.bg":true,"3.bg":true,"4.bg":true,"5.bg":true,"6.bg":true,"7.bg":true,"8.bg":true,"9.bg":true,"bh":true,"com.bh":true,"edu.bh":true,"net.bh":true,"org.bh":true,"gov.bh":true,"bi":true,"co.bi":true,"com.bi":true,"edu.bi":true,"or.bi":true,"org.bi":true,"biz":true,"bj":true,"asso.bj":true,"barreau.bj":true,"gouv.bj":true,"bm":true,"com.bm":true,"edu.bm":true,"gov.bm":true,"net.bm":true,"org.bm":true,"*.bn":true,"bo":true,"com.bo":true,"edu.bo":true,"gov.bo":true,"gob.bo":true,"int.bo":true,"org.bo":true,"net.bo":true,"mil.bo":true,"tv.bo":true,"br":true,"adm.br":true,"adv.br":true,"agr.br":true,"am.br":true,"arq.br":true,"art.br":true,"ato.br":true,"b.br":true,"bio.br":true,"blog.br":true,"bmd.br":true,"cim.br":true,"cng.br":true,"cnt.br":true,"com.br":true,"coop.br":true,"ecn.br":true,"eco.br":true,"edu.br":true,"emp.br":true,"eng.br":true,"esp.br":true,"etc.br":true,"eti.br":true,"far.br":true,"flog.br":true,"fm.br":true,"fnd.br":true,"fot.br":true,"fst.br":true,"g12.br":true,"ggf.br":true,"gov.br":true,"imb.br":true,"ind.br":true,"inf.br":true,"jor.br":true,"jus.br":true,"leg.br":true,"lel.br":true,"mat.br":true,"med.br":true,"mil.br":true,"mp.br":true,"mus.br":true,"net.br":true,"*.nom.br":true,"not.br":true,"ntr.br":true,"odo.br":true,"org.br":true,"ppg.br":true,"pro.br":true,"psc.br":true,"psi.br":true,"qsl.br":true,"radio.br":true,"rec.br":true,"slg.br":true,"srv.br":true,"taxi.br":true,"teo.br":true,"tmp.br":true,"trd.br":true,"tur.br":true,"tv.br":true,"vet.br":true,"vlog.br":true,"wiki.br":true,"zlg.br":true,"bs":true,"com.bs":true,"net.bs":true,"org.bs":true,"edu.bs":true,"gov.bs":true,"bt":true,"com.bt":true,"edu.bt":true,"gov.bt":true,"net.bt":true,"org.bt":true,"bv":true,"bw":true,"co.bw":true,"org.bw":true,"by":true,"gov.by":true,"mil.by":true,"com.by":true,"of.by":true,"bz":true,"com.bz":true,"net.bz":true,"org.bz":true,"edu.bz":true,"gov.bz":true,"ca":true,"ab.ca":true,"bc.ca":true,"mb.ca":true,"nb.ca":true,"nf.ca":true,"nl.ca":true,"ns.ca":true,"nt.ca":true,"nu.ca":true,"on.ca":true,"pe.ca":true,"qc.ca":true,"sk.ca":true,"yk.ca":true,"gc.ca":true,"cat":true,"cc":true,"cd":true,"gov.cd":true,"cf":true,"cg":true,"ch":true,"ci":true,"org.ci":true,"or.ci":true,"com.ci":true,"co.ci":true,"edu.ci":true,"ed.ci":true,"ac.ci":true,"net.ci":true,"go.ci":true,"asso.ci":true,"xn--aroport-bya.ci":true,"int.ci":true,"presse.ci":true,"md.ci":true,"gouv.ci":true,"*.ck":true,"www.ck":false,"cl":true,"gov.cl":true,"gob.cl":true,"co.cl":true,"mil.cl":true,"cm":true,"co.cm":true,"com.cm":true,"gov.cm":true,"net.cm":true,"cn":true,"ac.cn":true,"com.cn":true,"edu.cn":true,"gov.cn":true,"net.cn":true,"org.cn":true,"mil.cn":true,"xn--55qx5d.cn":true,"xn--io0a7i.cn":true,"xn--od0alg.cn":true,"ah.cn":true,"bj.cn":true,"cq.cn":true,"fj.cn":true,"gd.cn":true,"gs.cn":true,"gz.cn":true,"gx.cn":true,"ha.cn":true,"hb.cn":true,"he.cn":true,"hi.cn":true,"hl.cn":true,"hn.cn":true,"jl.cn":true,"js.cn":true,"jx.cn":true,"ln.cn":true,"nm.cn":true,"nx.cn":true,"qh.cn":true,"sc.cn":true,"sd.cn":true,"sh.cn":true,"sn.cn":true,"sx.cn":true,"tj.cn":true,"xj.cn":true,"xz.cn":true,"yn.cn":true,"zj.cn":true,"hk.cn":true,"mo.cn":true,"tw.cn":true,"co":true,"arts.co":true,"com.co":true,"edu.co":true,"firm.co":true,"gov.co":true,"info.co":true,"int.co":true,"mil.co":true,"net.co":true,"nom.co":true,"org.co":true,"rec.co":true,"web.co":true,"com":true,"coop":true,"cr":true,"ac.cr":true,"co.cr":true,"ed.cr":true,"fi.cr":true,"go.cr":true,"or.cr":true,"sa.cr":true,"cu":true,"com.cu":true,"edu.cu":true,"org.cu":true,"net.cu":true,"gov.cu":true,"inf.cu":true,"cv":true,"cw":true,"com.cw":true,"edu.cw":true,"net.cw":true,"org.cw":true,"cx":true,"gov.cx":true,"*.cy":true,"cz":true,"de":true,"dj":true,"dk":true,"dm":true,"com.dm":true,"net.dm":true,"org.dm":true,"edu.dm":true,"gov.dm":true,"do":true,"art.do":true,"com.do":true,"edu.do":true,"gob.do":true,"gov.do":true,"mil.do":true,"net.do":true,"org.do":true,"sld.do":true,"web.do":true,"dz":true,"com.dz":true,"org.dz":true,"net.dz":true,"gov.dz":true,"edu.dz":true,"asso.dz":true,"pol.dz":true,"art.dz":true,"ec":true,"com.ec":true,"info.ec":true,"net.ec":true,"fin.ec":true,"k12.ec":true,"med.ec":true,"pro.ec":true,"org.ec":true,"edu.ec":true,"gov.ec":true,"gob.ec":true,"mil.ec":true,"edu":true,"ee":true,"edu.ee":true,"gov.ee":true,"riik.ee":true,"lib.ee":true,"med.ee":true,"com.ee":true,"pri.ee":true,"aip.ee":true,"org.ee":true,"fie.ee":true,"eg":true,"com.eg":true,"edu.eg":true,"eun.eg":true,"gov.eg":true,"mil.eg":true,"name.eg":true,"net.eg":true,"org.eg":true,"sci.eg":true,"*.er":true,"es":true,"com.es":true,"nom.es":true,"org.es":true,"gob.es":true,"edu.es":true,"et":true,"com.et":true,"gov.et":true,"org.et":true,"edu.et":true,"biz.et":true,"name.et":true,"info.et":true,"eu":true,"fi":true,"aland.fi":true,"*.fj":true,"*.fk":true,"fm":true,"fo":true,"fr":true,"com.fr":true,"asso.fr":true,"nom.fr":true,"prd.fr":true,"presse.fr":true,"tm.fr":true,"aeroport.fr":true,"assedic.fr":true,"avocat.fr":true,"avoues.fr":true,"cci.fr":true,"chambagri.fr":true,"chirurgiens-dentistes.fr":true,"experts-comptables.fr":true,"geometre-expert.fr":true,"gouv.fr":true,"greta.fr":true,"huissier-justice.fr":true,"medecin.fr":true,"notaires.fr":true,"pharmacien.fr":true,"port.fr":true,"veterinaire.fr":true,"ga":true,"gb":true,"gd":true,"ge":true,"com.ge":true,"edu.ge":true,"gov.ge":true,"org.ge":true,"mil.ge":true,"net.ge":true,"pvt.ge":true,"gf":true,"gg":true,"co.gg":true,"net.gg":true,"org.gg":true,"gh":true,"com.gh":true,"edu.gh":true,"gov.gh":true,"org.gh":true,"mil.gh":true,"gi":true,"com.gi":true,"ltd.gi":true,"gov.gi":true,"mod.gi":true,"edu.gi":true,"org.gi":true,"gl":true,"gm":true,"gn":true,"ac.gn":true,"com.gn":true,"edu.gn":true,"gov.gn":true,"org.gn":true,"net.gn":true,"gov":true,"gp":true,"com.gp":true,"net.gp":true,"mobi.gp":true,"edu.gp":true,"org.gp":true,"asso.gp":true,"gq":true,"gr":true,"com.gr":true,"edu.gr":true,"net.gr":true,"org.gr":true,"gov.gr":true,"gs":true,"gt":true,"com.gt":true,"edu.gt":true,"gob.gt":true,"ind.gt":true,"mil.gt":true,"net.gt":true,"org.gt":true,"*.gu":true,"gw":true,"gy":true,"co.gy":true,"com.gy":true,"net.gy":true,"hk":true,"com.hk":true,"edu.hk":true,"gov.hk":true,"idv.hk":true,"net.hk":true,"org.hk":true,"xn--55qx5d.hk":true,"xn--wcvs22d.hk":true,"xn--lcvr32d.hk":true,"xn--mxtq1m.hk":true,"xn--gmqw5a.hk":true,"xn--ciqpn.hk":true,"xn--gmq050i.hk":true,"xn--zf0avx.hk":true,"xn--io0a7i.hk":true,"xn--mk0axi.hk":true,"xn--od0alg.hk":true,"xn--od0aq3b.hk":true,"xn--tn0ag.hk":true,"xn--uc0atv.hk":true,"xn--uc0ay4a.hk":true,"hm":true,"hn":true,"com.hn":true,"edu.hn":true,"org.hn":true,"net.hn":true,"mil.hn":true,"gob.hn":true,"hr":true,"iz.hr":true,"from.hr":true,"name.hr":true,"com.hr":true,"ht":true,"com.ht":true,"shop.ht":true,"firm.ht":true,"info.ht":true,"adult.ht":true,"net.ht":true,"pro.ht":true,"org.ht":true,"med.ht":true,"art.ht":true,"coop.ht":true,"pol.ht":true,"asso.ht":true,"edu.ht":true,"rel.ht":true,"gouv.ht":true,"perso.ht":true,"hu":true,"co.hu":true,"info.hu":true,"org.hu":true,"priv.hu":true,"sport.hu":true,"tm.hu":true,"2000.hu":true,"agrar.hu":true,"bolt.hu":true,"casino.hu":true,"city.hu":true,"erotica.hu":true,"erotika.hu":true,"film.hu":true,"forum.hu":true,"games.hu":true,"hotel.hu":true,"ingatlan.hu":true,"jogasz.hu":true,"konyvelo.hu":true,"lakas.hu":true,"media.hu":true,"news.hu":true,"reklam.hu":true,"sex.hu":true,"shop.hu":true,"suli.hu":true,"szex.hu":true,"tozsde.hu":true,"utazas.hu":true,"video.hu":true,"id":true,"ac.id":true,"biz.id":true,"co.id":true,"desa.id":true,"go.id":true,"mil.id":true,"my.id":true,"net.id":true,"or.id":true,"sch.id":true,"web.id":true,"ie":true,"gov.ie":true,"*.il":true,"im":true,"ac.im":true,"co.im":true,"com.im":true,"ltd.co.im":true,"net.im":true,"org.im":true,"plc.co.im":true,"tt.im":true,"tv.im":true,"in":true,"co.in":true,"firm.in":true,"net.in":true,"org.in":true,"gen.in":true,"ind.in":true,"nic.in":true,"ac.in":true,"edu.in":true,"res.in":true,"gov.in":true,"mil.in":true,"info":true,"int":true,"eu.int":true,"io":true,"com.io":true,"iq":true,"gov.iq":true,"edu.iq":true,"mil.iq":true,"com.iq":true,"org.iq":true,"net.iq":true,"ir":true,"ac.ir":true,"co.ir":true,"gov.ir":true,"id.ir":true,"net.ir":true,"org.ir":true,"sch.ir":true,"xn--mgba3a4f16a.ir":true,"xn--mgba3a4fra.ir":true,"is":true,"net.is":true,"com.is":true,"edu.is":true,"gov.is":true,"org.is":true,"int.is":true,"it":true,"gov.it":true,"edu.it":true,"abr.it":true,"abruzzo.it":true,"aosta-valley.it":true,"aostavalley.it":true,"bas.it":true,"basilicata.it":true,"cal.it":true,"calabria.it":true,"cam.it":true,"campania.it":true,"emilia-romagna.it":true,"emiliaromagna.it":true,"emr.it":true,"friuli-v-giulia.it":true,"friuli-ve-giulia.it":true,"friuli-vegiulia.it":true,"friuli-venezia-giulia.it":true,"friuli-veneziagiulia.it":true,"friuli-vgiulia.it":true,"friuliv-giulia.it":true,"friulive-giulia.it":true,"friulivegiulia.it":true,"friulivenezia-giulia.it":true,"friuliveneziagiulia.it":true,"friulivgiulia.it":true,"fvg.it":true,"laz.it":true,"lazio.it":true,"lig.it":true,"liguria.it":true,"lom.it":true,"lombardia.it":true,"lombardy.it":true,"lucania.it":true,"mar.it":true,"marche.it":true,"mol.it":true,"molise.it":true,"piedmont.it":true,"piemonte.it":true,"pmn.it":true,"pug.it":true,"puglia.it":true,"sar.it":true,"sardegna.it":true,"sardinia.it":true,"sic.it":true,"sicilia.it":true,"sicily.it":true,"taa.it":true,"tos.it":true,"toscana.it":true,"trentino-a-adige.it":true,"trentino-aadige.it":true,"trentino-alto-adige.it":true,"trentino-altoadige.it":true,"trentino-s-tirol.it":true,"trentino-stirol.it":true,"trentino-sud-tirol.it":true,"trentino-sudtirol.it":true,"trentino-sued-tirol.it":true,"trentino-suedtirol.it":true,"trentinoa-adige.it":true,"trentinoaadige.it":true,"trentinoalto-adige.it":true,"trentinoaltoadige.it":true,"trentinos-tirol.it":true,"trentinostirol.it":true,"trentinosud-tirol.it":true,"trentinosudtirol.it":true,"trentinosued-tirol.it":true,"trentinosuedtirol.it":true,"tuscany.it":true,"umb.it":true,"umbria.it":true,"val-d-aosta.it":true,"val-daosta.it":true,"vald-aosta.it":true,"valdaosta.it":true,"valle-aosta.it":true,"valle-d-aosta.it":true,"valle-daosta.it":true,"valleaosta.it":true,"valled-aosta.it":true,"valledaosta.it":true,"vallee-aoste.it":true,"valleeaoste.it":true,"vao.it":true,"vda.it":true,"ven.it":true,"veneto.it":true,"ag.it":true,"agrigento.it":true,"al.it":true,"alessandria.it":true,"alto-adige.it":true,"altoadige.it":true,"an.it":true,"ancona.it":true,"andria-barletta-trani.it":true,"andria-trani-barletta.it":true,"andriabarlettatrani.it":true,"andriatranibarletta.it":true,"ao.it":true,"aosta.it":true,"aoste.it":true,"ap.it":true,"aq.it":true,"aquila.it":true,"ar.it":true,"arezzo.it":true,"ascoli-piceno.it":true,"ascolipiceno.it":true,"asti.it":true,"at.it":true,"av.it":true,"avellino.it":true,"ba.it":true,"balsan.it":true,"bari.it":true,"barletta-trani-andria.it":true,"barlettatraniandria.it":true,"belluno.it":true,"benevento.it":true,"bergamo.it":true,"bg.it":true,"bi.it":true,"biella.it":true,"bl.it":true,"bn.it":true,"bo.it":true,"bologna.it":true,"bolzano.it":true,"bozen.it":true,"br.it":true,"brescia.it":true,"brindisi.it":true,"bs.it":true,"bt.it":true,"bz.it":true,"ca.it":true,"cagliari.it":true,"caltanissetta.it":true,"campidano-medio.it":true,"campidanomedio.it":true,"campobasso.it":true,"carbonia-iglesias.it":true,"carboniaiglesias.it":true,"carrara-massa.it":true,"carraramassa.it":true,"caserta.it":true,"catania.it":true,"catanzaro.it":true,"cb.it":true,"ce.it":true,"cesena-forli.it":true,"cesenaforli.it":true,"ch.it":true,"chieti.it":true,"ci.it":true,"cl.it":true,"cn.it":true,"co.it":true,"como.it":true,"cosenza.it":true,"cr.it":true,"cremona.it":true,"crotone.it":true,"cs.it":true,"ct.it":true,"cuneo.it":true,"cz.it":true,"dell-ogliastra.it":true,"dellogliastra.it":true,"en.it":true,"enna.it":true,"fc.it":true,"fe.it":true,"fermo.it":true,"ferrara.it":true,"fg.it":true,"fi.it":true,"firenze.it":true,"florence.it":true,"fm.it":true,"foggia.it":true,"forli-cesena.it":true,"forlicesena.it":true,"fr.it":true,"frosinone.it":true,"ge.it":true,"genoa.it":true,"genova.it":true,"go.it":true,"gorizia.it":true,"gr.it":true,"grosseto.it":true,"iglesias-carbonia.it":true,"iglesiascarbonia.it":true,"im.it":true,"imperia.it":true,"is.it":true,"isernia.it":true,"kr.it":true,"la-spezia.it":true,"laquila.it":true,"laspezia.it":true,"latina.it":true,"lc.it":true,"le.it":true,"lecce.it":true,"lecco.it":true,"li.it":true,"livorno.it":true,"lo.it":true,"lodi.it":true,"lt.it":true,"lu.it":true,"lucca.it":true,"macerata.it":true,"mantova.it":true,"massa-carrara.it":true,"massacarrara.it":true,"matera.it":true,"mb.it":true,"mc.it":true,"me.it":true,"medio-campidano.it":true,"mediocampidano.it":true,"messina.it":true,"mi.it":true,"milan.it":true,"milano.it":true,"mn.it":true,"mo.it":true,"modena.it":true,"monza-brianza.it":true,"monza-e-della-brianza.it":true,"monza.it":true,"monzabrianza.it":true,"monzaebrianza.it":true,"monzaedellabrianza.it":true,"ms.it":true,"mt.it":true,"na.it":true,"naples.it":true,"napoli.it":true,"no.it":true,"novara.it":true,"nu.it":true,"nuoro.it":true,"og.it":true,"ogliastra.it":true,"olbia-tempio.it":true,"olbiatempio.it":true,"or.it":true,"oristano.it":true,"ot.it":true,"pa.it":true,"padova.it":true,"padua.it":true,"palermo.it":true,"parma.it":true,"pavia.it":true,"pc.it":true,"pd.it":true,"pe.it":true,"perugia.it":true,"pesaro-urbino.it":true,"pesarourbino.it":true,"pescara.it":true,"pg.it":true,"pi.it":true,"piacenza.it":true,"pisa.it":true,"pistoia.it":true,"pn.it":true,"po.it":true,"pordenone.it":true,"potenza.it":true,"pr.it":true,"prato.it":true,"pt.it":true,"pu.it":true,"pv.it":true,"pz.it":true,"ra.it":true,"ragusa.it":true,"ravenna.it":true,"rc.it":true,"re.it":true,"reggio-calabria.it":true,"reggio-emilia.it":true,"reggiocalabria.it":true,"reggioemilia.it":true,"rg.it":true,"ri.it":true,"rieti.it":true,"rimini.it":true,"rm.it":true,"rn.it":true,"ro.it":true,"roma.it":true,"rome.it":true,"rovigo.it":true,"sa.it":true,"salerno.it":true,"sassari.it":true,"savona.it":true,"si.it":true,"siena.it":true,"siracusa.it":true,"so.it":true,"sondrio.it":true,"sp.it":true,"sr.it":true,"ss.it":true,"suedtirol.it":true,"sv.it":true,"ta.it":true,"taranto.it":true,"te.it":true,"tempio-olbia.it":true,"tempioolbia.it":true,"teramo.it":true,"terni.it":true,"tn.it":true,"to.it":true,"torino.it":true,"tp.it":true,"tr.it":true,"trani-andria-barletta.it":true,"trani-barletta-andria.it":true,"traniandriabarletta.it":true,"tranibarlettaandria.it":true,"trapani.it":true,"trentino.it":true,"trento.it":true,"treviso.it":true,"trieste.it":true,"ts.it":true,"turin.it":true,"tv.it":true,"ud.it":true,"udine.it":true,"urbino-pesaro.it":true,"urbinopesaro.it":true,"va.it":true,"varese.it":true,"vb.it":true,"vc.it":true,"ve.it":true,"venezia.it":true,"venice.it":true,"verbania.it":true,"vercelli.it":true,"verona.it":true,"vi.it":true,"vibo-valentia.it":true,"vibovalentia.it":true,"vicenza.it":true,"viterbo.it":true,"vr.it":true,"vs.it":true,"vt.it":true,"vv.it":true,"je":true,"co.je":true,"net.je":true,"org.je":true,"*.jm":true,"jo":true,"com.jo":true,"org.jo":true,"net.jo":true,"edu.jo":true,"sch.jo":true,"gov.jo":true,"mil.jo":true,"name.jo":true,"jobs":true,"jp":true,"ac.jp":true,"ad.jp":true,"co.jp":true,"ed.jp":true,"go.jp":true,"gr.jp":true,"lg.jp":true,"ne.jp":true,"or.jp":true,"aichi.jp":true,"akita.jp":true,"aomori.jp":true,"chiba.jp":true,"ehime.jp":true,"fukui.jp":true,"fukuoka.jp":true,"fukushima.jp":true,"gifu.jp":true,"gunma.jp":true,"hiroshima.jp":true,"hokkaido.jp":true,"hyogo.jp":true,"ibaraki.jp":true,"ishikawa.jp":true,"iwate.jp":true,"kagawa.jp":true,"kagoshima.jp":true,"kanagawa.jp":true,"kochi.jp":true,"kumamoto.jp":true,"kyoto.jp":true,"mie.jp":true,"miyagi.jp":true,"miyazaki.jp":true,"nagano.jp":true,"nagasaki.jp":true,"nara.jp":true,"niigata.jp":true,"oita.jp":true,"okayama.jp":true,"okinawa.jp":true,"osaka.jp":true,"saga.jp":true,"saitama.jp":true,"shiga.jp":true,"shimane.jp":true,"shizuoka.jp":true,"tochigi.jp":true,"tokushima.jp":true,"tokyo.jp":true,"tottori.jp":true,"toyama.jp":true,"wakayama.jp":true,"yamagata.jp":true,"yamaguchi.jp":true,"yamanashi.jp":true,"xn--4pvxs.jp":true,"xn--vgu402c.jp":true,"xn--c3s14m.jp":true,"xn--f6qx53a.jp":true,"xn--8pvr4u.jp":true,"xn--uist22h.jp":true,"xn--djrs72d6uy.jp":true,"xn--mkru45i.jp":true,"xn--0trq7p7nn.jp":true,"xn--8ltr62k.jp":true,"xn--2m4a15e.jp":true,"xn--efvn9s.jp":true,"xn--32vp30h.jp":true,"xn--4it797k.jp":true,"xn--1lqs71d.jp":true,"xn--5rtp49c.jp":true,"xn--5js045d.jp":true,"xn--ehqz56n.jp":true,"xn--1lqs03n.jp":true,"xn--qqqt11m.jp":true,"xn--kbrq7o.jp":true,"xn--pssu33l.jp":true,"xn--ntsq17g.jp":true,"xn--uisz3g.jp":true,"xn--6btw5a.jp":true,"xn--1ctwo.jp":true,"xn--6orx2r.jp":true,"xn--rht61e.jp":true,"xn--rht27z.jp":true,"xn--djty4k.jp":true,"xn--nit225k.jp":true,"xn--rht3d.jp":true,"xn--klty5x.jp":true,"xn--kltx9a.jp":true,"xn--kltp7d.jp":true,"xn--uuwu58a.jp":true,"xn--zbx025d.jp":true,"xn--ntso0iqx3a.jp":true,"xn--elqq16h.jp":true,"xn--4it168d.jp":true,"xn--klt787d.jp":true,"xn--rny31h.jp":true,"xn--7t0a264c.jp":true,"xn--5rtq34k.jp":true,"xn--k7yn95e.jp":true,"xn--tor131o.jp":true,"xn--d5qv7z876c.jp":true,"*.kawasaki.jp":true,"*.kitakyushu.jp":true,"*.kobe.jp":true,"*.nagoya.jp":true,"*.sapporo.jp":true,"*.sendai.jp":true,"*.yokohama.jp":true,"city.kawasaki.jp":false,"city.kitakyushu.jp":false,"city.kobe.jp":false,"city.nagoya.jp":false,"city.sapporo.jp":false,"city.sendai.jp":false,"city.yokohama.jp":false,"aisai.aichi.jp":true,"ama.aichi.jp":true,"anjo.aichi.jp":true,"asuke.aichi.jp":true,"chiryu.aichi.jp":true,"chita.aichi.jp":true,"fuso.aichi.jp":true,"gamagori.aichi.jp":true,"handa.aichi.jp":true,"hazu.aichi.jp":true,"hekinan.aichi.jp":true,"higashiura.aichi.jp":true,"ichinomiya.aichi.jp":true,"inazawa.aichi.jp":true,"inuyama.aichi.jp":true,"isshiki.aichi.jp":true,"iwakura.aichi.jp":true,"kanie.aichi.jp":true,"kariya.aichi.jp":true,"kasugai.aichi.jp":true,"kira.aichi.jp":true,"kiyosu.aichi.jp":true,"komaki.aichi.jp":true,"konan.aichi.jp":true,"kota.aichi.jp":true,"mihama.aichi.jp":true,"miyoshi.aichi.jp":true,"nishio.aichi.jp":true,"nisshin.aichi.jp":true,"obu.aichi.jp":true,"oguchi.aichi.jp":true,"oharu.aichi.jp":true,"okazaki.aichi.jp":true,"owariasahi.aichi.jp":true,"seto.aichi.jp":true,"shikatsu.aichi.jp":true,"shinshiro.aichi.jp":true,"shitara.aichi.jp":true,"tahara.aichi.jp":true,"takahama.aichi.jp":true,"tobishima.aichi.jp":true,"toei.aichi.jp":true,"togo.aichi.jp":true,"tokai.aichi.jp":true,"tokoname.aichi.jp":true,"toyoake.aichi.jp":true,"toyohashi.aichi.jp":true,"toyokawa.aichi.jp":true,"toyone.aichi.jp":true,"toyota.aichi.jp":true,"tsushima.aichi.jp":true,"yatomi.aichi.jp":true,"akita.akita.jp":true,"daisen.akita.jp":true,"fujisato.akita.jp":true,"gojome.akita.jp":true,"hachirogata.akita.jp":true,"happou.akita.jp":true,"higashinaruse.akita.jp":true,"honjo.akita.jp":true,"honjyo.akita.jp":true,"ikawa.akita.jp":true,"kamikoani.akita.jp":true,"kamioka.akita.jp":true,"katagami.akita.jp":true,"kazuno.akita.jp":true,"kitaakita.akita.jp":true,"kosaka.akita.jp":true,"kyowa.akita.jp":true,"misato.akita.jp":true,"mitane.akita.jp":true,"moriyoshi.akita.jp":true,"nikaho.akita.jp":true,"noshiro.akita.jp":true,"odate.akita.jp":true,"oga.akita.jp":true,"ogata.akita.jp":true,"semboku.akita.jp":true,"yokote.akita.jp":true,"yurihonjo.akita.jp":true,"aomori.aomori.jp":true,"gonohe.aomori.jp":true,"hachinohe.aomori.jp":true,"hashikami.aomori.jp":true,"hiranai.aomori.jp":true,"hirosaki.aomori.jp":true,"itayanagi.aomori.jp":true,"kuroishi.aomori.jp":true,"misawa.aomori.jp":true,"mutsu.aomori.jp":true,"nakadomari.aomori.jp":true,"noheji.aomori.jp":true,"oirase.aomori.jp":true,"owani.aomori.jp":true,"rokunohe.aomori.jp":true,"sannohe.aomori.jp":true,"shichinohe.aomori.jp":true,"shingo.aomori.jp":true,"takko.aomori.jp":true,"towada.aomori.jp":true,"tsugaru.aomori.jp":true,"tsuruta.aomori.jp":true,"abiko.chiba.jp":true,"asahi.chiba.jp":true,"chonan.chiba.jp":true,"chosei.chiba.jp":true,"choshi.chiba.jp":true,"chuo.chiba.jp":true,"funabashi.chiba.jp":true,"futtsu.chiba.jp":true,"hanamigawa.chiba.jp":true,"ichihara.chiba.jp":true,"ichikawa.chiba.jp":true,"ichinomiya.chiba.jp":true,"inzai.chiba.jp":true,"isumi.chiba.jp":true,"kamagaya.chiba.jp":true,"kamogawa.chiba.jp":true,"kashiwa.chiba.jp":true,"katori.chiba.jp":true,"katsuura.chiba.jp":true,"kimitsu.chiba.jp":true,"kisarazu.chiba.jp":true,"kozaki.chiba.jp":true,"kujukuri.chiba.jp":true,"kyonan.chiba.jp":true,"matsudo.chiba.jp":true,"midori.chiba.jp":true,"mihama.chiba.jp":true,"minamiboso.chiba.jp":true,"mobara.chiba.jp":true,"mutsuzawa.chiba.jp":true,"nagara.chiba.jp":true,"nagareyama.chiba.jp":true,"narashino.chiba.jp":true,"narita.chiba.jp":true,"noda.chiba.jp":true,"oamishirasato.chiba.jp":true,"omigawa.chiba.jp":true,"onjuku.chiba.jp":true,"otaki.chiba.jp":true,"sakae.chiba.jp":true,"sakura.chiba.jp":true,"shimofusa.chiba.jp":true,"shirako.chiba.jp":true,"shiroi.chiba.jp":true,"shisui.chiba.jp":true,"sodegaura.chiba.jp":true,"sosa.chiba.jp":true,"tako.chiba.jp":true,"tateyama.chiba.jp":true,"togane.chiba.jp":true,"tohnosho.chiba.jp":true,"tomisato.chiba.jp":true,"urayasu.chiba.jp":true,"yachimata.chiba.jp":true,"yachiyo.chiba.jp":true,"yokaichiba.chiba.jp":true,"yokoshibahikari.chiba.jp":true,"yotsukaido.chiba.jp":true,"ainan.ehime.jp":true,"honai.ehime.jp":true,"ikata.ehime.jp":true,"imabari.ehime.jp":true,"iyo.ehime.jp":true,"kamijima.ehime.jp":true,"kihoku.ehime.jp":true,"kumakogen.ehime.jp":true,"masaki.ehime.jp":true,"matsuno.ehime.jp":true,"matsuyama.ehime.jp":true,"namikata.ehime.jp":true,"niihama.ehime.jp":true,"ozu.ehime.jp":true,"saijo.ehime.jp":true,"seiyo.ehime.jp":true,"shikokuchuo.ehime.jp":true,"tobe.ehime.jp":true,"toon.ehime.jp":true,"uchiko.ehime.jp":true,"uwajima.ehime.jp":true,"yawatahama.ehime.jp":true,"echizen.fukui.jp":true,"eiheiji.fukui.jp":true,"fukui.fukui.jp":true,"ikeda.fukui.jp":true,"katsuyama.fukui.jp":true,"mihama.fukui.jp":true,"minamiechizen.fukui.jp":true,"obama.fukui.jp":true,"ohi.fukui.jp":true,"ono.fukui.jp":true,"sabae.fukui.jp":true,"sakai.fukui.jp":true,"takahama.fukui.jp":true,"tsuruga.fukui.jp":true,"wakasa.fukui.jp":true,"ashiya.fukuoka.jp":true,"buzen.fukuoka.jp":true,"chikugo.fukuoka.jp":true,"chikuho.fukuoka.jp":true,"chikujo.fukuoka.jp":true,"chikushino.fukuoka.jp":true,"chikuzen.fukuoka.jp":true,"chuo.fukuoka.jp":true,"dazaifu.fukuoka.jp":true,"fukuchi.fukuoka.jp":true,"hakata.fukuoka.jp":true,"higashi.fukuoka.jp":true,"hirokawa.fukuoka.jp":true,"hisayama.fukuoka.jp":true,"iizuka.fukuoka.jp":true,"inatsuki.fukuoka.jp":true,"kaho.fukuoka.jp":true,"kasuga.fukuoka.jp":true,"kasuya.fukuoka.jp":true,"kawara.fukuoka.jp":true,"keisen.fukuoka.jp":true,"koga.fukuoka.jp":true,"kurate.fukuoka.jp":true,"kurogi.fukuoka.jp":true,"kurume.fukuoka.jp":true,"minami.fukuoka.jp":true,"miyako.fukuoka.jp":true,"miyama.fukuoka.jp":true,"miyawaka.fukuoka.jp":true,"mizumaki.fukuoka.jp":true,"munakata.fukuoka.jp":true,"nakagawa.fukuoka.jp":true,"nakama.fukuoka.jp":true,"nishi.fukuoka.jp":true,"nogata.fukuoka.jp":true,"ogori.fukuoka.jp":true,"okagaki.fukuoka.jp":true,"okawa.fukuoka.jp":true,"oki.fukuoka.jp":true,"omuta.fukuoka.jp":true,"onga.fukuoka.jp":true,"onojo.fukuoka.jp":true,"oto.fukuoka.jp":true,"saigawa.fukuoka.jp":true,"sasaguri.fukuoka.jp":true,"shingu.fukuoka.jp":true,"shinyoshitomi.fukuoka.jp":true,"shonai.fukuoka.jp":true,"soeda.fukuoka.jp":true,"sue.fukuoka.jp":true,"tachiarai.fukuoka.jp":true,"tagawa.fukuoka.jp":true,"takata.fukuoka.jp":true,"toho.fukuoka.jp":true,"toyotsu.fukuoka.jp":true,"tsuiki.fukuoka.jp":true,"ukiha.fukuoka.jp":true,"umi.fukuoka.jp":true,"usui.fukuoka.jp":true,"yamada.fukuoka.jp":true,"yame.fukuoka.jp":true,"yanagawa.fukuoka.jp":true,"yukuhashi.fukuoka.jp":true,"aizubange.fukushima.jp":true,"aizumisato.fukushima.jp":true,"aizuwakamatsu.fukushima.jp":true,"asakawa.fukushima.jp":true,"bandai.fukushima.jp":true,"date.fukushima.jp":true,"fukushima.fukushima.jp":true,"furudono.fukushima.jp":true,"futaba.fukushima.jp":true,"hanawa.fukushima.jp":true,"higashi.fukushima.jp":true,"hirata.fukushima.jp":true,"hirono.fukushima.jp":true,"iitate.fukushima.jp":true,"inawashiro.fukushima.jp":true,"ishikawa.fukushima.jp":true,"iwaki.fukushima.jp":true,"izumizaki.fukushima.jp":true,"kagamiishi.fukushima.jp":true,"kaneyama.fukushima.jp":true,"kawamata.fukushima.jp":true,"kitakata.fukushima.jp":true,"kitashiobara.fukushima.jp":true,"koori.fukushima.jp":true,"koriyama.fukushima.jp":true,"kunimi.fukushima.jp":true,"miharu.fukushima.jp":true,"mishima.fukushima.jp":true,"namie.fukushima.jp":true,"nango.fukushima.jp":true,"nishiaizu.fukushima.jp":true,"nishigo.fukushima.jp":true,"okuma.fukushima.jp":true,"omotego.fukushima.jp":true,"ono.fukushima.jp":true,"otama.fukushima.jp":true,"samegawa.fukushima.jp":true,"shimogo.fukushima.jp":true,"shirakawa.fukushima.jp":true,"showa.fukushima.jp":true,"soma.fukushima.jp":true,"sukagawa.fukushima.jp":true,"taishin.fukushima.jp":true,"tamakawa.fukushima.jp":true,"tanagura.fukushima.jp":true,"tenei.fukushima.jp":true,"yabuki.fukushima.jp":true,"yamato.fukushima.jp":true,"yamatsuri.fukushima.jp":true,"yanaizu.fukushima.jp":true,"yugawa.fukushima.jp":true,"anpachi.gifu.jp":true,"ena.gifu.jp":true,"gifu.gifu.jp":true,"ginan.gifu.jp":true,"godo.gifu.jp":true,"gujo.gifu.jp":true,"hashima.gifu.jp":true,"hichiso.gifu.jp":true,"hida.gifu.jp":true,"higashishirakawa.gifu.jp":true,"ibigawa.gifu.jp":true,"ikeda.gifu.jp":true,"kakamigahara.gifu.jp":true,"kani.gifu.jp":true,"kasahara.gifu.jp":true,"kasamatsu.gifu.jp":true,"kawaue.gifu.jp":true,"kitagata.gifu.jp":true,"mino.gifu.jp":true,"minokamo.gifu.jp":true,"mitake.gifu.jp":true,"mizunami.gifu.jp":true,"motosu.gifu.jp":true,"nakatsugawa.gifu.jp":true,"ogaki.gifu.jp":true,"sakahogi.gifu.jp":true,"seki.gifu.jp":true,"sekigahara.gifu.jp":true,"shirakawa.gifu.jp":true,"tajimi.gifu.jp":true,"takayama.gifu.jp":true,"tarui.gifu.jp":true,"toki.gifu.jp":true,"tomika.gifu.jp":true,"wanouchi.gifu.jp":true,"yamagata.gifu.jp":true,"yaotsu.gifu.jp":true,"yoro.gifu.jp":true,"annaka.gunma.jp":true,"chiyoda.gunma.jp":true,"fujioka.gunma.jp":true,"higashiagatsuma.gunma.jp":true,"isesaki.gunma.jp":true,"itakura.gunma.jp":true,"kanna.gunma.jp":true,"kanra.gunma.jp":true,"katashina.gunma.jp":true,"kawaba.gunma.jp":true,"kiryu.gunma.jp":true,"kusatsu.gunma.jp":true,"maebashi.gunma.jp":true,"meiwa.gunma.jp":true,"midori.gunma.jp":true,"minakami.gunma.jp":true,"naganohara.gunma.jp":true,"nakanojo.gunma.jp":true,"nanmoku.gunma.jp":true,"numata.gunma.jp":true,"oizumi.gunma.jp":true,"ora.gunma.jp":true,"ota.gunma.jp":true,"shibukawa.gunma.jp":true,"shimonita.gunma.jp":true,"shinto.gunma.jp":true,"showa.gunma.jp":true,"takasaki.gunma.jp":true,"takayama.gunma.jp":true,"tamamura.gunma.jp":true,"tatebayashi.gunma.jp":true,"tomioka.gunma.jp":true,"tsukiyono.gunma.jp":true,"tsumagoi.gunma.jp":true,"ueno.gunma.jp":true,"yoshioka.gunma.jp":true,"asaminami.hiroshima.jp":true,"daiwa.hiroshima.jp":true,"etajima.hiroshima.jp":true,"fuchu.hiroshima.jp":true,"fukuyama.hiroshima.jp":true,"hatsukaichi.hiroshima.jp":true,"higashihiroshima.hiroshima.jp":true,"hongo.hiroshima.jp":true,"jinsekikogen.hiroshima.jp":true,"kaita.hiroshima.jp":true,"kui.hiroshima.jp":true,"kumano.hiroshima.jp":true,"kure.hiroshima.jp":true,"mihara.hiroshima.jp":true,"miyoshi.hiroshima.jp":true,"naka.hiroshima.jp":true,"onomichi.hiroshima.jp":true,"osakikamijima.hiroshima.jp":true,"otake.hiroshima.jp":true,"saka.hiroshima.jp":true,"sera.hiroshima.jp":true,"seranishi.hiroshima.jp":true,"shinichi.hiroshima.jp":true,"shobara.hiroshima.jp":true,"takehara.hiroshima.jp":true,"abashiri.hokkaido.jp":true,"abira.hokkaido.jp":true,"aibetsu.hokkaido.jp":true,"akabira.hokkaido.jp":true,"akkeshi.hokkaido.jp":true,"asahikawa.hokkaido.jp":true,"ashibetsu.hokkaido.jp":true,"ashoro.hokkaido.jp":true,"assabu.hokkaido.jp":true,"atsuma.hokkaido.jp":true,"bibai.hokkaido.jp":true,"biei.hokkaido.jp":true,"bifuka.hokkaido.jp":true,"bihoro.hokkaido.jp":true,"biratori.hokkaido.jp":true,"chippubetsu.hokkaido.jp":true,"chitose.hokkaido.jp":true,"date.hokkaido.jp":true,"ebetsu.hokkaido.jp":true,"embetsu.hokkaido.jp":true,"eniwa.hokkaido.jp":true,"erimo.hokkaido.jp":true,"esan.hokkaido.jp":true,"esashi.hokkaido.jp":true,"fukagawa.hokkaido.jp":true,"fukushima.hokkaido.jp":true,"furano.hokkaido.jp":true,"furubira.hokkaido.jp":true,"haboro.hokkaido.jp":true,"hakodate.hokkaido.jp":true,"hamatonbetsu.hokkaido.jp":true,"hidaka.hokkaido.jp":true,"higashikagura.hokkaido.jp":true,"higashikawa.hokkaido.jp":true,"hiroo.hokkaido.jp":true,"hokuryu.hokkaido.jp":true,"hokuto.hokkaido.jp":true,"honbetsu.hokkaido.jp":true,"horokanai.hokkaido.jp":true,"horonobe.hokkaido.jp":true,"ikeda.hokkaido.jp":true,"imakane.hokkaido.jp":true,"ishikari.hokkaido.jp":true,"iwamizawa.hokkaido.jp":true,"iwanai.hokkaido.jp":true,"kamifurano.hokkaido.jp":true,"kamikawa.hokkaido.jp":true,"kamishihoro.hokkaido.jp":true,"kamisunagawa.hokkaido.jp":true,"kamoenai.hokkaido.jp":true,"kayabe.hokkaido.jp":true,"kembuchi.hokkaido.jp":true,"kikonai.hokkaido.jp":true,"kimobetsu.hokkaido.jp":true,"kitahiroshima.hokkaido.jp":true,"kitami.hokkaido.jp":true,"kiyosato.hokkaido.jp":true,"koshimizu.hokkaido.jp":true,"kunneppu.hokkaido.jp":true,"kuriyama.hokkaido.jp":true,"kuromatsunai.hokkaido.jp":true,"kushiro.hokkaido.jp":true,"kutchan.hokkaido.jp":true,"kyowa.hokkaido.jp":true,"mashike.hokkaido.jp":true,"matsumae.hokkaido.jp":true,"mikasa.hokkaido.jp":true,"minamifurano.hokkaido.jp":true,"mombetsu.hokkaido.jp":true,"moseushi.hokkaido.jp":true,"mukawa.hokkaido.jp":true,"muroran.hokkaido.jp":true,"naie.hokkaido.jp":true,"nakagawa.hokkaido.jp":true,"nakasatsunai.hokkaido.jp":true,"nakatombetsu.hokkaido.jp":true,"nanae.hokkaido.jp":true,"nanporo.hokkaido.jp":true,"nayoro.hokkaido.jp":true,"nemuro.hokkaido.jp":true,"niikappu.hokkaido.jp":true,"niki.hokkaido.jp":true,"nishiokoppe.hokkaido.jp":true,"noboribetsu.hokkaido.jp":true,"numata.hokkaido.jp":true,"obihiro.hokkaido.jp":true,"obira.hokkaido.jp":true,"oketo.hokkaido.jp":true,"okoppe.hokkaido.jp":true,"otaru.hokkaido.jp":true,"otobe.hokkaido.jp":true,"otofuke.hokkaido.jp":true,"otoineppu.hokkaido.jp":true,"oumu.hokkaido.jp":true,"ozora.hokkaido.jp":true,"pippu.hokkaido.jp":true,"rankoshi.hokkaido.jp":true,"rebun.hokkaido.jp":true,"rikubetsu.hokkaido.jp":true,"rishiri.hokkaido.jp":true,"rishirifuji.hokkaido.jp":true,"saroma.hokkaido.jp":true,"sarufutsu.hokkaido.jp":true,"shakotan.hokkaido.jp":true,"shari.hokkaido.jp":true,"shibecha.hokkaido.jp":true,"shibetsu.hokkaido.jp":true,"shikabe.hokkaido.jp":true,"shikaoi.hokkaido.jp":true,"shimamaki.hokkaido.jp":true,"shimizu.hokkaido.jp":true,"shimokawa.hokkaido.jp":true,"shinshinotsu.hokkaido.jp":true,"shintoku.hokkaido.jp":true,"shiranuka.hokkaido.jp":true,"shiraoi.hokkaido.jp":true,"shiriuchi.hokkaido.jp":true,"sobetsu.hokkaido.jp":true,"sunagawa.hokkaido.jp":true,"taiki.hokkaido.jp":true,"takasu.hokkaido.jp":true,"takikawa.hokkaido.jp":true,"takinoue.hokkaido.jp":true,"teshikaga.hokkaido.jp":true,"tobetsu.hokkaido.jp":true,"tohma.hokkaido.jp":true,"tomakomai.hokkaido.jp":true,"tomari.hokkaido.jp":true,"toya.hokkaido.jp":true,"toyako.hokkaido.jp":true,"toyotomi.hokkaido.jp":true,"toyoura.hokkaido.jp":true,"tsubetsu.hokkaido.jp":true,"tsukigata.hokkaido.jp":true,"urakawa.hokkaido.jp":true,"urausu.hokkaido.jp":true,"uryu.hokkaido.jp":true,"utashinai.hokkaido.jp":true,"wakkanai.hokkaido.jp":true,"wassamu.hokkaido.jp":true,"yakumo.hokkaido.jp":true,"yoichi.hokkaido.jp":true,"aioi.hyogo.jp":true,"akashi.hyogo.jp":true,"ako.hyogo.jp":true,"amagasaki.hyogo.jp":true,"aogaki.hyogo.jp":true,"asago.hyogo.jp":true,"ashiya.hyogo.jp":true,"awaji.hyogo.jp":true,"fukusaki.hyogo.jp":true,"goshiki.hyogo.jp":true,"harima.hyogo.jp":true,"himeji.hyogo.jp":true,"ichikawa.hyogo.jp":true,"inagawa.hyogo.jp":true,"itami.hyogo.jp":true,"kakogawa.hyogo.jp":true,"kamigori.hyogo.jp":true,"kamikawa.hyogo.jp":true,"kasai.hyogo.jp":true,"kasuga.hyogo.jp":true,"kawanishi.hyogo.jp":true,"miki.hyogo.jp":true,"minamiawaji.hyogo.jp":true,"nishinomiya.hyogo.jp":true,"nishiwaki.hyogo.jp":true,"ono.hyogo.jp":true,"sanda.hyogo.jp":true,"sannan.hyogo.jp":true,"sasayama.hyogo.jp":true,"sayo.hyogo.jp":true,"shingu.hyogo.jp":true,"shinonsen.hyogo.jp":true,"shiso.hyogo.jp":true,"sumoto.hyogo.jp":true,"taishi.hyogo.jp":true,"taka.hyogo.jp":true,"takarazuka.hyogo.jp":true,"takasago.hyogo.jp":true,"takino.hyogo.jp":true,"tamba.hyogo.jp":true,"tatsuno.hyogo.jp":true,"toyooka.hyogo.jp":true,"yabu.hyogo.jp":true,"yashiro.hyogo.jp":true,"yoka.hyogo.jp":true,"yokawa.hyogo.jp":true,"ami.ibaraki.jp":true,"asahi.ibaraki.jp":true,"bando.ibaraki.jp":true,"chikusei.ibaraki.jp":true,"daigo.ibaraki.jp":true,"fujishiro.ibaraki.jp":true,"hitachi.ibaraki.jp":true,"hitachinaka.ibaraki.jp":true,"hitachiomiya.ibaraki.jp":true,"hitachiota.ibaraki.jp":true,"ibaraki.ibaraki.jp":true,"ina.ibaraki.jp":true,"inashiki.ibaraki.jp":true,"itako.ibaraki.jp":true,"iwama.ibaraki.jp":true,"joso.ibaraki.jp":true,"kamisu.ibaraki.jp":true,"kasama.ibaraki.jp":true,"kashima.ibaraki.jp":true,"kasumigaura.ibaraki.jp":true,"koga.ibaraki.jp":true,"miho.ibaraki.jp":true,"mito.ibaraki.jp":true,"moriya.ibaraki.jp":true,"naka.ibaraki.jp":true,"namegata.ibaraki.jp":true,"oarai.ibaraki.jp":true,"ogawa.ibaraki.jp":true,"omitama.ibaraki.jp":true,"ryugasaki.ibaraki.jp":true,"sakai.ibaraki.jp":true,"sakuragawa.ibaraki.jp":true,"shimodate.ibaraki.jp":true,"shimotsuma.ibaraki.jp":true,"shirosato.ibaraki.jp":true,"sowa.ibaraki.jp":true,"suifu.ibaraki.jp":true,"takahagi.ibaraki.jp":true,"tamatsukuri.ibaraki.jp":true,"tokai.ibaraki.jp":true,"tomobe.ibaraki.jp":true,"tone.ibaraki.jp":true,"toride.ibaraki.jp":true,"tsuchiura.ibaraki.jp":true,"tsukuba.ibaraki.jp":true,"uchihara.ibaraki.jp":true,"ushiku.ibaraki.jp":true,"yachiyo.ibaraki.jp":true,"yamagata.ibaraki.jp":true,"yawara.ibaraki.jp":true,"yuki.ibaraki.jp":true,"anamizu.ishikawa.jp":true,"hakui.ishikawa.jp":true,"hakusan.ishikawa.jp":true,"kaga.ishikawa.jp":true,"kahoku.ishikawa.jp":true,"kanazawa.ishikawa.jp":true,"kawakita.ishikawa.jp":true,"komatsu.ishikawa.jp":true,"nakanoto.ishikawa.jp":true,"nanao.ishikawa.jp":true,"nomi.ishikawa.jp":true,"nonoichi.ishikawa.jp":true,"noto.ishikawa.jp":true,"shika.ishikawa.jp":true,"suzu.ishikawa.jp":true,"tsubata.ishikawa.jp":true,"tsurugi.ishikawa.jp":true,"uchinada.ishikawa.jp":true,"wajima.ishikawa.jp":true,"fudai.iwate.jp":true,"fujisawa.iwate.jp":true,"hanamaki.iwate.jp":true,"hiraizumi.iwate.jp":true,"hirono.iwate.jp":true,"ichinohe.iwate.jp":true,"ichinoseki.iwate.jp":true,"iwaizumi.iwate.jp":true,"iwate.iwate.jp":true,"joboji.iwate.jp":true,"kamaishi.iwate.jp":true,"kanegasaki.iwate.jp":true,"karumai.iwate.jp":true,"kawai.iwate.jp":true,"kitakami.iwate.jp":true,"kuji.iwate.jp":true,"kunohe.iwate.jp":true,"kuzumaki.iwate.jp":true,"miyako.iwate.jp":true,"mizusawa.iwate.jp":true,"morioka.iwate.jp":true,"ninohe.iwate.jp":true,"noda.iwate.jp":true,"ofunato.iwate.jp":true,"oshu.iwate.jp":true,"otsuchi.iwate.jp":true,"rikuzentakata.iwate.jp":true,"shiwa.iwate.jp":true,"shizukuishi.iwate.jp":true,"sumita.iwate.jp":true,"tanohata.iwate.jp":true,"tono.iwate.jp":true,"yahaba.iwate.jp":true,"yamada.iwate.jp":true,"ayagawa.kagawa.jp":true,"higashikagawa.kagawa.jp":true,"kanonji.kagawa.jp":true,"kotohira.kagawa.jp":true,"manno.kagawa.jp":true,"marugame.kagawa.jp":true,"mitoyo.kagawa.jp":true,"naoshima.kagawa.jp":true,"sanuki.kagawa.jp":true,"tadotsu.kagawa.jp":true,"takamatsu.kagawa.jp":true,"tonosho.kagawa.jp":true,"uchinomi.kagawa.jp":true,"utazu.kagawa.jp":true,"zentsuji.kagawa.jp":true,"akune.kagoshima.jp":true,"amami.kagoshima.jp":true,"hioki.kagoshima.jp":true,"isa.kagoshima.jp":true,"isen.kagoshima.jp":true,"izumi.kagoshima.jp":true,"kagoshima.kagoshima.jp":true,"kanoya.kagoshima.jp":true,"kawanabe.kagoshima.jp":true,"kinko.kagoshima.jp":true,"kouyama.kagoshima.jp":true,"makurazaki.kagoshima.jp":true,"matsumoto.kagoshima.jp":true,"minamitane.kagoshima.jp":true,"nakatane.kagoshima.jp":true,"nishinoomote.kagoshima.jp":true,"satsumasendai.kagoshima.jp":true,"soo.kagoshima.jp":true,"tarumizu.kagoshima.jp":true,"yusui.kagoshima.jp":true,"aikawa.kanagawa.jp":true,"atsugi.kanagawa.jp":true,"ayase.kanagawa.jp":true,"chigasaki.kanagawa.jp":true,"ebina.kanagawa.jp":true,"fujisawa.kanagawa.jp":true,"hadano.kanagawa.jp":true,"hakone.kanagawa.jp":true,"hiratsuka.kanagawa.jp":true,"isehara.kanagawa.jp":true,"kaisei.kanagawa.jp":true,"kamakura.kanagawa.jp":true,"kiyokawa.kanagawa.jp":true,"matsuda.kanagawa.jp":true,"minamiashigara.kanagawa.jp":true,"miura.kanagawa.jp":true,"nakai.kanagawa.jp":true,"ninomiya.kanagawa.jp":true,"odawara.kanagawa.jp":true,"oi.kanagawa.jp":true,"oiso.kanagawa.jp":true,"sagamihara.kanagawa.jp":true,"samukawa.kanagawa.jp":true,"tsukui.kanagawa.jp":true,"yamakita.kanagawa.jp":true,"yamato.kanagawa.jp":true,"yokosuka.kanagawa.jp":true,"yugawara.kanagawa.jp":true,"zama.kanagawa.jp":true,"zushi.kanagawa.jp":true,"aki.kochi.jp":true,"geisei.kochi.jp":true,"hidaka.kochi.jp":true,"higashitsuno.kochi.jp":true,"ino.kochi.jp":true,"kagami.kochi.jp":true,"kami.kochi.jp":true,"kitagawa.kochi.jp":true,"kochi.kochi.jp":true,"mihara.kochi.jp":true,"motoyama.kochi.jp":true,"muroto.kochi.jp":true,"nahari.kochi.jp":true,"nakamura.kochi.jp":true,"nankoku.kochi.jp":true,"nishitosa.kochi.jp":true,"niyodogawa.kochi.jp":true,"ochi.kochi.jp":true,"okawa.kochi.jp":true,"otoyo.kochi.jp":true,"otsuki.kochi.jp":true,"sakawa.kochi.jp":true,"sukumo.kochi.jp":true,"susaki.kochi.jp":true,"tosa.kochi.jp":true,"tosashimizu.kochi.jp":true,"toyo.kochi.jp":true,"tsuno.kochi.jp":true,"umaji.kochi.jp":true,"yasuda.kochi.jp":true,"yusuhara.kochi.jp":true,"amakusa.kumamoto.jp":true,"arao.kumamoto.jp":true,"aso.kumamoto.jp":true,"choyo.kumamoto.jp":true,"gyokuto.kumamoto.jp":true,"hitoyoshi.kumamoto.jp":true,"kamiamakusa.kumamoto.jp":true,"kashima.kumamoto.jp":true,"kikuchi.kumamoto.jp":true,"kosa.kumamoto.jp":true,"kumamoto.kumamoto.jp":true,"mashiki.kumamoto.jp":true,"mifune.kumamoto.jp":true,"minamata.kumamoto.jp":true,"minamioguni.kumamoto.jp":true,"nagasu.kumamoto.jp":true,"nishihara.kumamoto.jp":true,"oguni.kumamoto.jp":true,"ozu.kumamoto.jp":true,"sumoto.kumamoto.jp":true,"takamori.kumamoto.jp":true,"uki.kumamoto.jp":true,"uto.kumamoto.jp":true,"yamaga.kumamoto.jp":true,"yamato.kumamoto.jp":true,"yatsushiro.kumamoto.jp":true,"ayabe.kyoto.jp":true,"fukuchiyama.kyoto.jp":true,"higashiyama.kyoto.jp":true,"ide.kyoto.jp":true,"ine.kyoto.jp":true,"joyo.kyoto.jp":true,"kameoka.kyoto.jp":true,"kamo.kyoto.jp":true,"kita.kyoto.jp":true,"kizu.kyoto.jp":true,"kumiyama.kyoto.jp":true,"kyotamba.kyoto.jp":true,"kyotanabe.kyoto.jp":true,"kyotango.kyoto.jp":true,"maizuru.kyoto.jp":true,"minami.kyoto.jp":true,"minamiyamashiro.kyoto.jp":true,"miyazu.kyoto.jp":true,"muko.kyoto.jp":true,"nagaokakyo.kyoto.jp":true,"nakagyo.kyoto.jp":true,"nantan.kyoto.jp":true,"oyamazaki.kyoto.jp":true,"sakyo.kyoto.jp":true,"seika.kyoto.jp":true,"tanabe.kyoto.jp":true,"uji.kyoto.jp":true,"ujitawara.kyoto.jp":true,"wazuka.kyoto.jp":true,"yamashina.kyoto.jp":true,"yawata.kyoto.jp":true,"asahi.mie.jp":true,"inabe.mie.jp":true,"ise.mie.jp":true,"kameyama.mie.jp":true,"kawagoe.mie.jp":true,"kiho.mie.jp":true,"kisosaki.mie.jp":true,"kiwa.mie.jp":true,"komono.mie.jp":true,"kumano.mie.jp":true,"kuwana.mie.jp":true,"matsusaka.mie.jp":true,"meiwa.mie.jp":true,"mihama.mie.jp":true,"minamiise.mie.jp":true,"misugi.mie.jp":true,"miyama.mie.jp":true,"nabari.mie.jp":true,"shima.mie.jp":true,"suzuka.mie.jp":true,"tado.mie.jp":true,"taiki.mie.jp":true,"taki.mie.jp":true,"tamaki.mie.jp":true,"toba.mie.jp":true,"tsu.mie.jp":true,"udono.mie.jp":true,"ureshino.mie.jp":true,"watarai.mie.jp":true,"yokkaichi.mie.jp":true,"furukawa.miyagi.jp":true,"higashimatsushima.miyagi.jp":true,"ishinomaki.miyagi.jp":true,"iwanuma.miyagi.jp":true,"kakuda.miyagi.jp":true,"kami.miyagi.jp":true,"kawasaki.miyagi.jp":true,"kesennuma.miyagi.jp":true,"marumori.miyagi.jp":true,"matsushima.miyagi.jp":true,"minamisanriku.miyagi.jp":true,"misato.miyagi.jp":true,"murata.miyagi.jp":true,"natori.miyagi.jp":true,"ogawara.miyagi.jp":true,"ohira.miyagi.jp":true,"onagawa.miyagi.jp":true,"osaki.miyagi.jp":true,"rifu.miyagi.jp":true,"semine.miyagi.jp":true,"shibata.miyagi.jp":true,"shichikashuku.miyagi.jp":true,"shikama.miyagi.jp":true,"shiogama.miyagi.jp":true,"shiroishi.miyagi.jp":true,"tagajo.miyagi.jp":true,"taiwa.miyagi.jp":true,"tome.miyagi.jp":true,"tomiya.miyagi.jp":true,"wakuya.miyagi.jp":true,"watari.miyagi.jp":true,"yamamoto.miyagi.jp":true,"zao.miyagi.jp":true,"aya.miyazaki.jp":true,"ebino.miyazaki.jp":true,"gokase.miyazaki.jp":true,"hyuga.miyazaki.jp":true,"kadogawa.miyazaki.jp":true,"kawaminami.miyazaki.jp":true,"kijo.miyazaki.jp":true,"kitagawa.miyazaki.jp":true,"kitakata.miyazaki.jp":true,"kitaura.miyazaki.jp":true,"kobayashi.miyazaki.jp":true,"kunitomi.miyazaki.jp":true,"kushima.miyazaki.jp":true,"mimata.miyazaki.jp":true,"miyakonojo.miyazaki.jp":true,"miyazaki.miyazaki.jp":true,"morotsuka.miyazaki.jp":true,"nichinan.miyazaki.jp":true,"nishimera.miyazaki.jp":true,"nobeoka.miyazaki.jp":true,"saito.miyazaki.jp":true,"shiiba.miyazaki.jp":true,"shintomi.miyazaki.jp":true,"takaharu.miyazaki.jp":true,"takanabe.miyazaki.jp":true,"takazaki.miyazaki.jp":true,"tsuno.miyazaki.jp":true,"achi.nagano.jp":true,"agematsu.nagano.jp":true,"anan.nagano.jp":true,"aoki.nagano.jp":true,"asahi.nagano.jp":true,"azumino.nagano.jp":true,"chikuhoku.nagano.jp":true,"chikuma.nagano.jp":true,"chino.nagano.jp":true,"fujimi.nagano.jp":true,"hakuba.nagano.jp":true,"hara.nagano.jp":true,"hiraya.nagano.jp":true,"iida.nagano.jp":true,"iijima.nagano.jp":true,"iiyama.nagano.jp":true,"iizuna.nagano.jp":true,"ikeda.nagano.jp":true,"ikusaka.nagano.jp":true,"ina.nagano.jp":true,"karuizawa.nagano.jp":true,"kawakami.nagano.jp":true,"kiso.nagano.jp":true,"kisofukushima.nagano.jp":true,"kitaaiki.nagano.jp":true,"komagane.nagano.jp":true,"komoro.nagano.jp":true,"matsukawa.nagano.jp":true,"matsumoto.nagano.jp":true,"miasa.nagano.jp":true,"minamiaiki.nagano.jp":true,"minamimaki.nagano.jp":true,"minamiminowa.nagano.jp":true,"minowa.nagano.jp":true,"miyada.nagano.jp":true,"miyota.nagano.jp":true,"mochizuki.nagano.jp":true,"nagano.nagano.jp":true,"nagawa.nagano.jp":true,"nagiso.nagano.jp":true,"nakagawa.nagano.jp":true,"nakano.nagano.jp":true,"nozawaonsen.nagano.jp":true,"obuse.nagano.jp":true,"ogawa.nagano.jp":true,"okaya.nagano.jp":true,"omachi.nagano.jp":true,"omi.nagano.jp":true,"ookuwa.nagano.jp":true,"ooshika.nagano.jp":true,"otaki.nagano.jp":true,"otari.nagano.jp":true,"sakae.nagano.jp":true,"sakaki.nagano.jp":true,"saku.nagano.jp":true,"sakuho.nagano.jp":true,"shimosuwa.nagano.jp":true,"shinanomachi.nagano.jp":true,"shiojiri.nagano.jp":true,"suwa.nagano.jp":true,"suzaka.nagano.jp":true,"takagi.nagano.jp":true,"takamori.nagano.jp":true,"takayama.nagano.jp":true,"tateshina.nagano.jp":true,"tatsuno.nagano.jp":true,"togakushi.nagano.jp":true,"togura.nagano.jp":true,"tomi.nagano.jp":true,"ueda.nagano.jp":true,"wada.nagano.jp":true,"yamagata.nagano.jp":true,"yamanouchi.nagano.jp":true,"yasaka.nagano.jp":true,"yasuoka.nagano.jp":true,"chijiwa.nagasaki.jp":true,"futsu.nagasaki.jp":true,"goto.nagasaki.jp":true,"hasami.nagasaki.jp":true,"hirado.nagasaki.jp":true,"iki.nagasaki.jp":true,"isahaya.nagasaki.jp":true,"kawatana.nagasaki.jp":true,"kuchinotsu.nagasaki.jp":true,"matsuura.nagasaki.jp":true,"nagasaki.nagasaki.jp":true,"obama.nagasaki.jp":true,"omura.nagasaki.jp":true,"oseto.nagasaki.jp":true,"saikai.nagasaki.jp":true,"sasebo.nagasaki.jp":true,"seihi.nagasaki.jp":true,"shimabara.nagasaki.jp":true,"shinkamigoto.nagasaki.jp":true,"togitsu.nagasaki.jp":true,"tsushima.nagasaki.jp":true,"unzen.nagasaki.jp":true,"ando.nara.jp":true,"gose.nara.jp":true,"heguri.nara.jp":true,"higashiyoshino.nara.jp":true,"ikaruga.nara.jp":true,"ikoma.nara.jp":true,"kamikitayama.nara.jp":true,"kanmaki.nara.jp":true,"kashiba.nara.jp":true,"kashihara.nara.jp":true,"katsuragi.nara.jp":true,"kawai.nara.jp":true,"kawakami.nara.jp":true,"kawanishi.nara.jp":true,"koryo.nara.jp":true,"kurotaki.nara.jp":true,"mitsue.nara.jp":true,"miyake.nara.jp":true,"nara.nara.jp":true,"nosegawa.nara.jp":true,"oji.nara.jp":true,"ouda.nara.jp":true,"oyodo.nara.jp":true,"sakurai.nara.jp":true,"sango.nara.jp":true,"shimoichi.nara.jp":true,"shimokitayama.nara.jp":true,"shinjo.nara.jp":true,"soni.nara.jp":true,"takatori.nara.jp":true,"tawaramoto.nara.jp":true,"tenkawa.nara.jp":true,"tenri.nara.jp":true,"uda.nara.jp":true,"yamatokoriyama.nara.jp":true,"yamatotakada.nara.jp":true,"yamazoe.nara.jp":true,"yoshino.nara.jp":true,"aga.niigata.jp":true,"agano.niigata.jp":true,"gosen.niigata.jp":true,"itoigawa.niigata.jp":true,"izumozaki.niigata.jp":true,"joetsu.niigata.jp":true,"kamo.niigata.jp":true,"kariwa.niigata.jp":true,"kashiwazaki.niigata.jp":true,"minamiuonuma.niigata.jp":true,"mitsuke.niigata.jp":true,"muika.niigata.jp":true,"murakami.niigata.jp":true,"myoko.niigata.jp":true,"nagaoka.niigata.jp":true,"niigata.niigata.jp":true,"ojiya.niigata.jp":true,"omi.niigata.jp":true,"sado.niigata.jp":true,"sanjo.niigata.jp":true,"seiro.niigata.jp":true,"seirou.niigata.jp":true,"sekikawa.niigata.jp":true,"shibata.niigata.jp":true,"tagami.niigata.jp":true,"tainai.niigata.jp":true,"tochio.niigata.jp":true,"tokamachi.niigata.jp":true,"tsubame.niigata.jp":true,"tsunan.niigata.jp":true,"uonuma.niigata.jp":true,"yahiko.niigata.jp":true,"yoita.niigata.jp":true,"yuzawa.niigata.jp":true,"beppu.oita.jp":true,"bungoono.oita.jp":true,"bungotakada.oita.jp":true,"hasama.oita.jp":true,"hiji.oita.jp":true,"himeshima.oita.jp":true,"hita.oita.jp":true,"kamitsue.oita.jp":true,"kokonoe.oita.jp":true,"kuju.oita.jp":true,"kunisaki.oita.jp":true,"kusu.oita.jp":true,"oita.oita.jp":true,"saiki.oita.jp":true,"taketa.oita.jp":true,"tsukumi.oita.jp":true,"usa.oita.jp":true,"usuki.oita.jp":true,"yufu.oita.jp":true,"akaiwa.okayama.jp":true,"asakuchi.okayama.jp":true,"bizen.okayama.jp":true,"hayashima.okayama.jp":true,"ibara.okayama.jp":true,"kagamino.okayama.jp":true,"kasaoka.okayama.jp":true,"kibichuo.okayama.jp":true,"kumenan.okayama.jp":true,"kurashiki.okayama.jp":true,"maniwa.okayama.jp":true,"misaki.okayama.jp":true,"nagi.okayama.jp":true,"niimi.okayama.jp":true,"nishiawakura.okayama.jp":true,"okayama.okayama.jp":true,"satosho.okayama.jp":true,"setouchi.okayama.jp":true,"shinjo.okayama.jp":true,"shoo.okayama.jp":true,"soja.okayama.jp":true,"takahashi.okayama.jp":true,"tamano.okayama.jp":true,"tsuyama.okayama.jp":true,"wake.okayama.jp":true,"yakage.okayama.jp":true,"aguni.okinawa.jp":true,"ginowan.okinawa.jp":true,"ginoza.okinawa.jp":true,"gushikami.okinawa.jp":true,"haebaru.okinawa.jp":true,"higashi.okinawa.jp":true,"hirara.okinawa.jp":true,"iheya.okinawa.jp":true,"ishigaki.okinawa.jp":true,"ishikawa.okinawa.jp":true,"itoman.okinawa.jp":true,"izena.okinawa.jp":true,"kadena.okinawa.jp":true,"kin.okinawa.jp":true,"kitadaito.okinawa.jp":true,"kitanakagusuku.okinawa.jp":true,"kumejima.okinawa.jp":true,"kunigami.okinawa.jp":true,"minamidaito.okinawa.jp":true,"motobu.okinawa.jp":true,"nago.okinawa.jp":true,"naha.okinawa.jp":true,"nakagusuku.okinawa.jp":true,"nakijin.okinawa.jp":true,"nanjo.okinawa.jp":true,"nishihara.okinawa.jp":true,"ogimi.okinawa.jp":true,"okinawa.okinawa.jp":true,"onna.okinawa.jp":true,"shimoji.okinawa.jp":true,"taketomi.okinawa.jp":true,"tarama.okinawa.jp":true,"tokashiki.okinawa.jp":true,"tomigusuku.okinawa.jp":true,"tonaki.okinawa.jp":true,"urasoe.okinawa.jp":true,"uruma.okinawa.jp":true,"yaese.okinawa.jp":true,"yomitan.okinawa.jp":true,"yonabaru.okinawa.jp":true,"yonaguni.okinawa.jp":true,"zamami.okinawa.jp":true,"abeno.osaka.jp":true,"chihayaakasaka.osaka.jp":true,"chuo.osaka.jp":true,"daito.osaka.jp":true,"fujiidera.osaka.jp":true,"habikino.osaka.jp":true,"hannan.osaka.jp":true,"higashiosaka.osaka.jp":true,"higashisumiyoshi.osaka.jp":true,"higashiyodogawa.osaka.jp":true,"hirakata.osaka.jp":true,"ibaraki.osaka.jp":true,"ikeda.osaka.jp":true,"izumi.osaka.jp":true,"izumiotsu.osaka.jp":true,"izumisano.osaka.jp":true,"kadoma.osaka.jp":true,"kaizuka.osaka.jp":true,"kanan.osaka.jp":true,"kashiwara.osaka.jp":true,"katano.osaka.jp":true,"kawachinagano.osaka.jp":true,"kishiwada.osaka.jp":true,"kita.osaka.jp":true,"kumatori.osaka.jp":true,"matsubara.osaka.jp":true,"minato.osaka.jp":true,"minoh.osaka.jp":true,"misaki.osaka.jp":true,"moriguchi.osaka.jp":true,"neyagawa.osaka.jp":true,"nishi.osaka.jp":true,"nose.osaka.jp":true,"osakasayama.osaka.jp":true,"sakai.osaka.jp":true,"sayama.osaka.jp":true,"sennan.osaka.jp":true,"settsu.osaka.jp":true,"shijonawate.osaka.jp":true,"shimamoto.osaka.jp":true,"suita.osaka.jp":true,"tadaoka.osaka.jp":true,"taishi.osaka.jp":true,"tajiri.osaka.jp":true,"takaishi.osaka.jp":true,"takatsuki.osaka.jp":true,"tondabayashi.osaka.jp":true,"toyonaka.osaka.jp":true,"toyono.osaka.jp":true,"yao.osaka.jp":true,"ariake.saga.jp":true,"arita.saga.jp":true,"fukudomi.saga.jp":true,"genkai.saga.jp":true,"hamatama.saga.jp":true,"hizen.saga.jp":true,"imari.saga.jp":true,"kamimine.saga.jp":true,"kanzaki.saga.jp":true,"karatsu.saga.jp":true,"kashima.saga.jp":true,"kitagata.saga.jp":true,"kitahata.saga.jp":true,"kiyama.saga.jp":true,"kouhoku.saga.jp":true,"kyuragi.saga.jp":true,"nishiarita.saga.jp":true,"ogi.saga.jp":true,"omachi.saga.jp":true,"ouchi.saga.jp":true,"saga.saga.jp":true,"shiroishi.saga.jp":true,"taku.saga.jp":true,"tara.saga.jp":true,"tosu.saga.jp":true,"yoshinogari.saga.jp":true,"arakawa.saitama.jp":true,"asaka.saitama.jp":true,"chichibu.saitama.jp":true,"fujimi.saitama.jp":true,"fujimino.saitama.jp":true,"fukaya.saitama.jp":true,"hanno.saitama.jp":true,"hanyu.saitama.jp":true,"hasuda.saitama.jp":true,"hatogaya.saitama.jp":true,"hatoyama.saitama.jp":true,"hidaka.saitama.jp":true,"higashichichibu.saitama.jp":true,"higashimatsuyama.saitama.jp":true,"honjo.saitama.jp":true,"ina.saitama.jp":true,"iruma.saitama.jp":true,"iwatsuki.saitama.jp":true,"kamiizumi.saitama.jp":true,"kamikawa.saitama.jp":true,"kamisato.saitama.jp":true,"kasukabe.saitama.jp":true,"kawagoe.saitama.jp":true,"kawaguchi.saitama.jp":true,"kawajima.saitama.jp":true,"kazo.saitama.jp":true,"kitamoto.saitama.jp":true,"koshigaya.saitama.jp":true,"kounosu.saitama.jp":true,"kuki.saitama.jp":true,"kumagaya.saitama.jp":true,"matsubushi.saitama.jp":true,"minano.saitama.jp":true,"misato.saitama.jp":true,"miyashiro.saitama.jp":true,"miyoshi.saitama.jp":true,"moroyama.saitama.jp":true,"nagatoro.saitama.jp":true,"namegawa.saitama.jp":true,"niiza.saitama.jp":true,"ogano.saitama.jp":true,"ogawa.saitama.jp":true,"ogose.saitama.jp":true,"okegawa.saitama.jp":true,"omiya.saitama.jp":true,"otaki.saitama.jp":true,"ranzan.saitama.jp":true,"ryokami.saitama.jp":true,"saitama.saitama.jp":true,"sakado.saitama.jp":true,"satte.saitama.jp":true,"sayama.saitama.jp":true,"shiki.saitama.jp":true,"shiraoka.saitama.jp":true,"soka.saitama.jp":true,"sugito.saitama.jp":true,"toda.saitama.jp":true,"tokigawa.saitama.jp":true,"tokorozawa.saitama.jp":true,"tsurugashima.saitama.jp":true,"urawa.saitama.jp":true,"warabi.saitama.jp":true,"yashio.saitama.jp":true,"yokoze.saitama.jp":true,"yono.saitama.jp":true,"yorii.saitama.jp":true,"yoshida.saitama.jp":true,"yoshikawa.saitama.jp":true,"yoshimi.saitama.jp":true,"aisho.shiga.jp":true,"gamo.shiga.jp":true,"higashiomi.shiga.jp":true,"hikone.shiga.jp":true,"koka.shiga.jp":true,"konan.shiga.jp":true,"kosei.shiga.jp":true,"koto.shiga.jp":true,"kusatsu.shiga.jp":true,"maibara.shiga.jp":true,"moriyama.shiga.jp":true,"nagahama.shiga.jp":true,"nishiazai.shiga.jp":true,"notogawa.shiga.jp":true,"omihachiman.shiga.jp":true,"otsu.shiga.jp":true,"ritto.shiga.jp":true,"ryuoh.shiga.jp":true,"takashima.shiga.jp":true,"takatsuki.shiga.jp":true,"torahime.shiga.jp":true,"toyosato.shiga.jp":true,"yasu.shiga.jp":true,"akagi.shimane.jp":true,"ama.shimane.jp":true,"gotsu.shimane.jp":true,"hamada.shimane.jp":true,"higashiizumo.shimane.jp":true,"hikawa.shimane.jp":true,"hikimi.shimane.jp":true,"izumo.shimane.jp":true,"kakinoki.shimane.jp":true,"masuda.shimane.jp":true,"matsue.shimane.jp":true,"misato.shimane.jp":true,"nishinoshima.shimane.jp":true,"ohda.shimane.jp":true,"okinoshima.shimane.jp":true,"okuizumo.shimane.jp":true,"shimane.shimane.jp":true,"tamayu.shimane.jp":true,"tsuwano.shimane.jp":true,"unnan.shimane.jp":true,"yakumo.shimane.jp":true,"yasugi.shimane.jp":true,"yatsuka.shimane.jp":true,"arai.shizuoka.jp":true,"atami.shizuoka.jp":true,"fuji.shizuoka.jp":true,"fujieda.shizuoka.jp":true,"fujikawa.shizuoka.jp":true,"fujinomiya.shizuoka.jp":true,"fukuroi.shizuoka.jp":true,"gotemba.shizuoka.jp":true,"haibara.shizuoka.jp":true,"hamamatsu.shizuoka.jp":true,"higashiizu.shizuoka.jp":true,"ito.shizuoka.jp":true,"iwata.shizuoka.jp":true,"izu.shizuoka.jp":true,"izunokuni.shizuoka.jp":true,"kakegawa.shizuoka.jp":true,"kannami.shizuoka.jp":true,"kawanehon.shizuoka.jp":true,"kawazu.shizuoka.jp":true,"kikugawa.shizuoka.jp":true,"kosai.shizuoka.jp":true,"makinohara.shizuoka.jp":true,"matsuzaki.shizuoka.jp":true,"minamiizu.shizuoka.jp":true,"mishima.shizuoka.jp":true,"morimachi.shizuoka.jp":true,"nishiizu.shizuoka.jp":true,"numazu.shizuoka.jp":true,"omaezaki.shizuoka.jp":true,"shimada.shizuoka.jp":true,"shimizu.shizuoka.jp":true,"shimoda.shizuoka.jp":true,"shizuoka.shizuoka.jp":true,"susono.shizuoka.jp":true,"yaizu.shizuoka.jp":true,"yoshida.shizuoka.jp":true,"ashikaga.tochigi.jp":true,"bato.tochigi.jp":true,"haga.tochigi.jp":true,"ichikai.tochigi.jp":true,"iwafune.tochigi.jp":true,"kaminokawa.tochigi.jp":true,"kanuma.tochigi.jp":true,"karasuyama.tochigi.jp":true,"kuroiso.tochigi.jp":true,"mashiko.tochigi.jp":true,"mibu.tochigi.jp":true,"moka.tochigi.jp":true,"motegi.tochigi.jp":true,"nasu.tochigi.jp":true,"nasushiobara.tochigi.jp":true,"nikko.tochigi.jp":true,"nishikata.tochigi.jp":true,"nogi.tochigi.jp":true,"ohira.tochigi.jp":true,"ohtawara.tochigi.jp":true,"oyama.tochigi.jp":true,"sakura.tochigi.jp":true,"sano.tochigi.jp":true,"shimotsuke.tochigi.jp":true,"shioya.tochigi.jp":true,"takanezawa.tochigi.jp":true,"tochigi.tochigi.jp":true,"tsuga.tochigi.jp":true,"ujiie.tochigi.jp":true,"utsunomiya.tochigi.jp":true,"yaita.tochigi.jp":true,"aizumi.tokushima.jp":true,"anan.tokushima.jp":true,"ichiba.tokushima.jp":true,"itano.tokushima.jp":true,"kainan.tokushima.jp":true,"komatsushima.tokushima.jp":true,"matsushige.tokushima.jp":true,"mima.tokushima.jp":true,"minami.tokushima.jp":true,"miyoshi.tokushima.jp":true,"mugi.tokushima.jp":true,"nakagawa.tokushima.jp":true,"naruto.tokushima.jp":true,"sanagochi.tokushima.jp":true,"shishikui.tokushima.jp":true,"tokushima.tokushima.jp":true,"wajiki.tokushima.jp":true,"adachi.tokyo.jp":true,"akiruno.tokyo.jp":true,"akishima.tokyo.jp":true,"aogashima.tokyo.jp":true,"arakawa.tokyo.jp":true,"bunkyo.tokyo.jp":true,"chiyoda.tokyo.jp":true,"chofu.tokyo.jp":true,"chuo.tokyo.jp":true,"edogawa.tokyo.jp":true,"fuchu.tokyo.jp":true,"fussa.tokyo.jp":true,"hachijo.tokyo.jp":true,"hachioji.tokyo.jp":true,"hamura.tokyo.jp":true,"higashikurume.tokyo.jp":true,"higashimurayama.tokyo.jp":true,"higashiyamato.tokyo.jp":true,"hino.tokyo.jp":true,"hinode.tokyo.jp":true,"hinohara.tokyo.jp":true,"inagi.tokyo.jp":true,"itabashi.tokyo.jp":true,"katsushika.tokyo.jp":true,"kita.tokyo.jp":true,"kiyose.tokyo.jp":true,"kodaira.tokyo.jp":true,"koganei.tokyo.jp":true,"kokubunji.tokyo.jp":true,"komae.tokyo.jp":true,"koto.tokyo.jp":true,"kouzushima.tokyo.jp":true,"kunitachi.tokyo.jp":true,"machida.tokyo.jp":true,"meguro.tokyo.jp":true,"minato.tokyo.jp":true,"mitaka.tokyo.jp":true,"mizuho.tokyo.jp":true,"musashimurayama.tokyo.jp":true,"musashino.tokyo.jp":true,"nakano.tokyo.jp":true,"nerima.tokyo.jp":true,"ogasawara.tokyo.jp":true,"okutama.tokyo.jp":true,"ome.tokyo.jp":true,"oshima.tokyo.jp":true,"ota.tokyo.jp":true,"setagaya.tokyo.jp":true,"shibuya.tokyo.jp":true,"shinagawa.tokyo.jp":true,"shinjuku.tokyo.jp":true,"suginami.tokyo.jp":true,"sumida.tokyo.jp":true,"tachikawa.tokyo.jp":true,"taito.tokyo.jp":true,"tama.tokyo.jp":true,"toshima.tokyo.jp":true,"chizu.tottori.jp":true,"hino.tottori.jp":true,"kawahara.tottori.jp":true,"koge.tottori.jp":true,"kotoura.tottori.jp":true,"misasa.tottori.jp":true,"nanbu.tottori.jp":true,"nichinan.tottori.jp":true,"sakaiminato.tottori.jp":true,"tottori.tottori.jp":true,"wakasa.tottori.jp":true,"yazu.tottori.jp":true,"yonago.tottori.jp":true,"asahi.toyama.jp":true,"fuchu.toyama.jp":true,"fukumitsu.toyama.jp":true,"funahashi.toyama.jp":true,"himi.toyama.jp":true,"imizu.toyama.jp":true,"inami.toyama.jp":true,"johana.toyama.jp":true,"kamiichi.toyama.jp":true,"kurobe.toyama.jp":true,"nakaniikawa.toyama.jp":true,"namerikawa.toyama.jp":true,"nanto.toyama.jp":true,"nyuzen.toyama.jp":true,"oyabe.toyama.jp":true,"taira.toyama.jp":true,"takaoka.toyama.jp":true,"tateyama.toyama.jp":true,"toga.toyama.jp":true,"tonami.toyama.jp":true,"toyama.toyama.jp":true,"unazuki.toyama.jp":true,"uozu.toyama.jp":true,"yamada.toyama.jp":true,"arida.wakayama.jp":true,"aridagawa.wakayama.jp":true,"gobo.wakayama.jp":true,"hashimoto.wakayama.jp":true,"hidaka.wakayama.jp":true,"hirogawa.wakayama.jp":true,"inami.wakayama.jp":true,"iwade.wakayama.jp":true,"kainan.wakayama.jp":true,"kamitonda.wakayama.jp":true,"katsuragi.wakayama.jp":true,"kimino.wakayama.jp":true,"kinokawa.wakayama.jp":true,"kitayama.wakayama.jp":true,"koya.wakayama.jp":true,"koza.wakayama.jp":true,"kozagawa.wakayama.jp":true,"kudoyama.wakayama.jp":true,"kushimoto.wakayama.jp":true,"mihama.wakayama.jp":true,"misato.wakayama.jp":true,"nachikatsuura.wakayama.jp":true,"shingu.wakayama.jp":true,"shirahama.wakayama.jp":true,"taiji.wakayama.jp":true,"tanabe.wakayama.jp":true,"wakayama.wakayama.jp":true,"yuasa.wakayama.jp":true,"yura.wakayama.jp":true,"asahi.yamagata.jp":true,"funagata.yamagata.jp":true,"higashine.yamagata.jp":true,"iide.yamagata.jp":true,"kahoku.yamagata.jp":true,"kaminoyama.yamagata.jp":true,"kaneyama.yamagata.jp":true,"kawanishi.yamagata.jp":true,"mamurogawa.yamagata.jp":true,"mikawa.yamagata.jp":true,"murayama.yamagata.jp":true,"nagai.yamagata.jp":true,"nakayama.yamagata.jp":true,"nanyo.yamagata.jp":true,"nishikawa.yamagata.jp":true,"obanazawa.yamagata.jp":true,"oe.yamagata.jp":true,"oguni.yamagata.jp":true,"ohkura.yamagata.jp":true,"oishida.yamagata.jp":true,"sagae.yamagata.jp":true,"sakata.yamagata.jp":true,"sakegawa.yamagata.jp":true,"shinjo.yamagata.jp":true,"shirataka.yamagata.jp":true,"shonai.yamagata.jp":true,"takahata.yamagata.jp":true,"tendo.yamagata.jp":true,"tozawa.yamagata.jp":true,"tsuruoka.yamagata.jp":true,"yamagata.yamagata.jp":true,"yamanobe.yamagata.jp":true,"yonezawa.yamagata.jp":true,"yuza.yamagata.jp":true,"abu.yamaguchi.jp":true,"hagi.yamaguchi.jp":true,"hikari.yamaguchi.jp":true,"hofu.yamaguchi.jp":true,"iwakuni.yamaguchi.jp":true,"kudamatsu.yamaguchi.jp":true,"mitou.yamaguchi.jp":true,"nagato.yamaguchi.jp":true,"oshima.yamaguchi.jp":true,"shimonoseki.yamaguchi.jp":true,"shunan.yamaguchi.jp":true,"tabuse.yamaguchi.jp":true,"tokuyama.yamaguchi.jp":true,"toyota.yamaguchi.jp":true,"ube.yamaguchi.jp":true,"yuu.yamaguchi.jp":true,"chuo.yamanashi.jp":true,"doshi.yamanashi.jp":true,"fuefuki.yamanashi.jp":true,"fujikawa.yamanashi.jp":true,"fujikawaguchiko.yamanashi.jp":true,"fujiyoshida.yamanashi.jp":true,"hayakawa.yamanashi.jp":true,"hokuto.yamanashi.jp":true,"ichikawamisato.yamanashi.jp":true,"kai.yamanashi.jp":true,"kofu.yamanashi.jp":true,"koshu.yamanashi.jp":true,"kosuge.yamanashi.jp":true,"minami-alps.yamanashi.jp":true,"minobu.yamanashi.jp":true,"nakamichi.yamanashi.jp":true,"nanbu.yamanashi.jp":true,"narusawa.yamanashi.jp":true,"nirasaki.yamanashi.jp":true,"nishikatsura.yamanashi.jp":true,"oshino.yamanashi.jp":true,"otsuki.yamanashi.jp":true,"showa.yamanashi.jp":true,"tabayama.yamanashi.jp":true,"tsuru.yamanashi.jp":true,"uenohara.yamanashi.jp":true,"yamanakako.yamanashi.jp":true,"yamanashi.yamanashi.jp":true,"*.ke":true,"kg":true,"org.kg":true,"net.kg":true,"com.kg":true,"edu.kg":true,"gov.kg":true,"mil.kg":true,"*.kh":true,"ki":true,"edu.ki":true,"biz.ki":true,"net.ki":true,"org.ki":true,"gov.ki":true,"info.ki":true,"com.ki":true,"km":true,"org.km":true,"nom.km":true,"gov.km":true,"prd.km":true,"tm.km":true,"edu.km":true,"mil.km":true,"ass.km":true,"com.km":true,"coop.km":true,"asso.km":true,"presse.km":true,"medecin.km":true,"notaires.km":true,"pharmaciens.km":true,"veterinaire.km":true,"gouv.km":true,"kn":true,"net.kn":true,"org.kn":true,"edu.kn":true,"gov.kn":true,"kp":true,"com.kp":true,"edu.kp":true,"gov.kp":true,"org.kp":true,"rep.kp":true,"tra.kp":true,"kr":true,"ac.kr":true,"co.kr":true,"es.kr":true,"go.kr":true,"hs.kr":true,"kg.kr":true,"mil.kr":true,"ms.kr":true,"ne.kr":true,"or.kr":true,"pe.kr":true,"re.kr":true,"sc.kr":true,"busan.kr":true,"chungbuk.kr":true,"chungnam.kr":true,"daegu.kr":true,"daejeon.kr":true,"gangwon.kr":true,"gwangju.kr":true,"gyeongbuk.kr":true,"gyeonggi.kr":true,"gyeongnam.kr":true,"incheon.kr":true,"jeju.kr":true,"jeonbuk.kr":true,"jeonnam.kr":true,"seoul.kr":true,"ulsan.kr":true,"*.kw":true,"ky":true,"edu.ky":true,"gov.ky":true,"com.ky":true,"org.ky":true,"net.ky":true,"kz":true,"org.kz":true,"edu.kz":true,"net.kz":true,"gov.kz":true,"mil.kz":true,"com.kz":true,"la":true,"int.la":true,"net.la":true,"info.la":true,"edu.la":true,"gov.la":true,"per.la":true,"com.la":true,"org.la":true,"lb":true,"com.lb":true,"edu.lb":true,"gov.lb":true,"net.lb":true,"org.lb":true,"lc":true,"com.lc":true,"net.lc":true,"co.lc":true,"org.lc":true,"edu.lc":true,"gov.lc":true,"li":true,"lk":true,"gov.lk":true,"sch.lk":true,"net.lk":true,"int.lk":true,"com.lk":true,"org.lk":true,"edu.lk":true,"ngo.lk":true,"soc.lk":true,"web.lk":true,"ltd.lk":true,"assn.lk":true,"grp.lk":true,"hotel.lk":true,"lr":true,"com.lr":true,"edu.lr":true,"gov.lr":true,"org.lr":true,"net.lr":true,"ls":true,"co.ls":true,"org.ls":true,"lt":true,"gov.lt":true,"lu":true,"lv":true,"com.lv":true,"edu.lv":true,"gov.lv":true,"org.lv":true,"mil.lv":true,"id.lv":true,"net.lv":true,"asn.lv":true,"conf.lv":true,"ly":true,"com.ly":true,"net.ly":true,"gov.ly":true,"plc.ly":true,"edu.ly":true,"sch.ly":true,"med.ly":true,"org.ly":true,"id.ly":true,"ma":true,"co.ma":true,"net.ma":true,"gov.ma":true,"org.ma":true,"ac.ma":true,"press.ma":true,"mc":true,"tm.mc":true,"asso.mc":true,"md":true,"me":true,"co.me":true,"net.me":true,"org.me":true,"edu.me":true,"ac.me":true,"gov.me":true,"its.me":true,"priv.me":true,"mg":true,"org.mg":true,"nom.mg":true,"gov.mg":true,"prd.mg":true,"tm.mg":true,"edu.mg":true,"mil.mg":true,"com.mg":true,"mh":true,"mil":true,"mk":true,"com.mk":true,"org.mk":true,"net.mk":true,"edu.mk":true,"gov.mk":true,"inf.mk":true,"name.mk":true,"ml":true,"com.ml":true,"edu.ml":true,"gouv.ml":true,"gov.ml":true,"net.ml":true,"org.ml":true,"presse.ml":true,"*.mm":true,"mn":true,"gov.mn":true,"edu.mn":true,"org.mn":true,"mo":true,"com.mo":true,"net.mo":true,"org.mo":true,"edu.mo":true,"gov.mo":true,"mobi":true,"mp":true,"mq":true,"mr":true,"gov.mr":true,"ms":true,"com.ms":true,"edu.ms":true,"gov.ms":true,"net.ms":true,"org.ms":true,"mt":true,"com.mt":true,"edu.mt":true,"net.mt":true,"org.mt":true,"mu":true,"com.mu":true,"net.mu":true,"org.mu":true,"gov.mu":true,"ac.mu":true,"co.mu":true,"or.mu":true,"museum":true,"academy.museum":true,"agriculture.museum":true,"air.museum":true,"airguard.museum":true,"alabama.museum":true,"alaska.museum":true,"amber.museum":true,"ambulance.museum":true,"american.museum":true,"americana.museum":true,"americanantiques.museum":true,"americanart.museum":true,"amsterdam.museum":true,"and.museum":true,"annefrank.museum":true,"anthro.museum":true,"anthropology.museum":true,"antiques.museum":true,"aquarium.museum":true,"arboretum.museum":true,"archaeological.museum":true,"archaeology.museum":true,"architecture.museum":true,"art.museum":true,"artanddesign.museum":true,"artcenter.museum":true,"artdeco.museum":true,"arteducation.museum":true,"artgallery.museum":true,"arts.museum":true,"artsandcrafts.museum":true,"asmatart.museum":true,"assassination.museum":true,"assisi.museum":true,"association.museum":true,"astronomy.museum":true,"atlanta.museum":true,"austin.museum":true,"australia.museum":true,"automotive.museum":true,"aviation.museum":true,"axis.museum":true,"badajoz.museum":true,"baghdad.museum":true,"bahn.museum":true,"bale.museum":true,"baltimore.museum":true,"barcelona.museum":true,"baseball.museum":true,"basel.museum":true,"baths.museum":true,"bauern.museum":true,"beauxarts.museum":true,"beeldengeluid.museum":true,"bellevue.museum":true,"bergbau.museum":true,"berkeley.museum":true,"berlin.museum":true,"bern.museum":true,"bible.museum":true,"bilbao.museum":true,"bill.museum":true,"birdart.museum":true,"birthplace.museum":true,"bonn.museum":true,"boston.museum":true,"botanical.museum":true,"botanicalgarden.museum":true,"botanicgarden.museum":true,"botany.museum":true,"brandywinevalley.museum":true,"brasil.museum":true,"bristol.museum":true,"british.museum":true,"britishcolumbia.museum":true,"broadcast.museum":true,"brunel.museum":true,"brussel.museum":true,"brussels.museum":true,"bruxelles.museum":true,"building.museum":true,"burghof.museum":true,"bus.museum":true,"bushey.museum":true,"cadaques.museum":true,"california.museum":true,"cambridge.museum":true,"can.museum":true,"canada.museum":true,"capebreton.museum":true,"carrier.museum":true,"cartoonart.museum":true,"casadelamoneda.museum":true,"castle.museum":true,"castres.museum":true,"celtic.museum":true,"center.museum":true,"chattanooga.museum":true,"cheltenham.museum":true,"chesapeakebay.museum":true,"chicago.museum":true,"children.museum":true,"childrens.museum":true,"childrensgarden.museum":true,"chiropractic.museum":true,"chocolate.museum":true,"christiansburg.museum":true,"cincinnati.museum":true,"cinema.museum":true,"circus.museum":true,"civilisation.museum":true,"civilization.museum":true,"civilwar.museum":true,"clinton.museum":true,"clock.museum":true,"coal.museum":true,"coastaldefence.museum":true,"cody.museum":true,"coldwar.museum":true,"collection.museum":true,"colonialwilliamsburg.museum":true,"coloradoplateau.museum":true,"columbia.museum":true,"columbus.museum":true,"communication.museum":true,"communications.museum":true,"community.museum":true,"computer.museum":true,"computerhistory.museum":true,"xn--comunicaes-v6a2o.museum":true,"contemporary.museum":true,"contemporaryart.museum":true,"convent.museum":true,"copenhagen.museum":true,"corporation.museum":true,"xn--correios-e-telecomunicaes-ghc29a.museum":true,"corvette.museum":true,"costume.museum":true,"countryestate.museum":true,"county.museum":true,"crafts.museum":true,"cranbrook.museum":true,"creation.museum":true,"cultural.museum":true,"culturalcenter.museum":true,"culture.museum":true,"cyber.museum":true,"cymru.museum":true,"dali.museum":true,"dallas.museum":true,"database.museum":true,"ddr.museum":true,"decorativearts.museum":true,"delaware.museum":true,"delmenhorst.museum":true,"denmark.museum":true,"depot.museum":true,"design.museum":true,"detroit.museum":true,"dinosaur.museum":true,"discovery.museum":true,"dolls.museum":true,"donostia.museum":true,"durham.museum":true,"eastafrica.museum":true,"eastcoast.museum":true,"education.museum":true,"educational.museum":true,"egyptian.museum":true,"eisenbahn.museum":true,"elburg.museum":true,"elvendrell.museum":true,"embroidery.museum":true,"encyclopedic.museum":true,"england.museum":true,"entomology.museum":true,"environment.museum":true,"environmentalconservation.museum":true,"epilepsy.museum":true,"essex.museum":true,"estate.museum":true,"ethnology.museum":true,"exeter.museum":true,"exhibition.museum":true,"family.museum":true,"farm.museum":true,"farmequipment.museum":true,"farmers.museum":true,"farmstead.museum":true,"field.museum":true,"figueres.museum":true,"filatelia.museum":true,"film.museum":true,"fineart.museum":true,"finearts.museum":true,"finland.museum":true,"flanders.museum":true,"florida.museum":true,"force.museum":true,"fortmissoula.museum":true,"fortworth.museum":true,"foundation.museum":true,"francaise.museum":true,"frankfurt.museum":true,"franziskaner.museum":true,"freemasonry.museum":true,"freiburg.museum":true,"fribourg.museum":true,"frog.museum":true,"fundacio.museum":true,"furniture.museum":true,"gallery.museum":true,"garden.museum":true,"gateway.museum":true,"geelvinck.museum":true,"gemological.museum":true,"geology.museum":true,"georgia.museum":true,"giessen.museum":true,"glas.museum":true,"glass.museum":true,"gorge.museum":true,"grandrapids.museum":true,"graz.museum":true,"guernsey.museum":true,"halloffame.museum":true,"hamburg.museum":true,"handson.museum":true,"harvestcelebration.museum":true,"hawaii.museum":true,"health.museum":true,"heimatunduhren.museum":true,"hellas.museum":true,"helsinki.museum":true,"hembygdsforbund.museum":true,"heritage.museum":true,"histoire.museum":true,"historical.museum":true,"historicalsociety.museum":true,"historichouses.museum":true,"historisch.museum":true,"historisches.museum":true,"history.museum":true,"historyofscience.museum":true,"horology.museum":true,"house.museum":true,"humanities.museum":true,"illustration.museum":true,"imageandsound.museum":true,"indian.museum":true,"indiana.museum":true,"indianapolis.museum":true,"indianmarket.museum":true,"intelligence.museum":true,"interactive.museum":true,"iraq.museum":true,"iron.museum":true,"isleofman.museum":true,"jamison.museum":true,"jefferson.museum":true,"jerusalem.museum":true,"jewelry.museum":true,"jewish.museum":true,"jewishart.museum":true,"jfk.museum":true,"journalism.museum":true,"judaica.museum":true,"judygarland.museum":true,"juedisches.museum":true,"juif.museum":true,"karate.museum":true,"karikatur.museum":true,"kids.museum":true,"koebenhavn.museum":true,"koeln.museum":true,"kunst.museum":true,"kunstsammlung.museum":true,"kunstunddesign.museum":true,"labor.museum":true,"labour.museum":true,"lajolla.museum":true,"lancashire.museum":true,"landes.museum":true,"lans.museum":true,"xn--lns-qla.museum":true,"larsson.museum":true,"lewismiller.museum":true,"lincoln.museum":true,"linz.museum":true,"living.museum":true,"livinghistory.museum":true,"localhistory.museum":true,"london.museum":true,"losangeles.museum":true,"louvre.museum":true,"loyalist.museum":true,"lucerne.museum":true,"luxembourg.museum":true,"luzern.museum":true,"mad.museum":true,"madrid.museum":true,"mallorca.museum":true,"manchester.museum":true,"mansion.museum":true,"mansions.museum":true,"manx.museum":true,"marburg.museum":true,"maritime.museum":true,"maritimo.museum":true,"maryland.museum":true,"marylhurst.museum":true,"media.museum":true,"medical.museum":true,"medizinhistorisches.museum":true,"meeres.museum":true,"memorial.museum":true,"mesaverde.museum":true,"michigan.museum":true,"midatlantic.museum":true,"military.museum":true,"mill.museum":true,"miners.museum":true,"mining.museum":true,"minnesota.museum":true,"missile.museum":true,"missoula.museum":true,"modern.museum":true,"moma.museum":true,"money.museum":true,"monmouth.museum":true,"monticello.museum":true,"montreal.museum":true,"moscow.museum":true,"motorcycle.museum":true,"muenchen.museum":true,"muenster.museum":true,"mulhouse.museum":true,"muncie.museum":true,"museet.museum":true,"museumcenter.museum":true,"museumvereniging.museum":true,"music.museum":true,"national.museum":true,"nationalfirearms.museum":true,"nationalheritage.museum":true,"nativeamerican.museum":true,"naturalhistory.museum":true,"naturalhistorymuseum.museum":true,"naturalsciences.museum":true,"nature.museum":true,"naturhistorisches.museum":true,"natuurwetenschappen.museum":true,"naumburg.museum":true,"naval.museum":true,"nebraska.museum":true,"neues.museum":true,"newhampshire.museum":true,"newjersey.museum":true,"newmexico.museum":true,"newport.museum":true,"newspaper.museum":true,"newyork.museum":true,"niepce.museum":true,"norfolk.museum":true,"north.museum":true,"nrw.museum":true,"nuernberg.museum":true,"nuremberg.museum":true,"nyc.museum":true,"nyny.museum":true,"oceanographic.museum":true,"oceanographique.museum":true,"omaha.museum":true,"online.museum":true,"ontario.museum":true,"openair.museum":true,"oregon.museum":true,"oregontrail.museum":true,"otago.museum":true,"oxford.museum":true,"pacific.museum":true,"paderborn.museum":true,"palace.museum":true,"paleo.museum":true,"palmsprings.museum":true,"panama.museum":true,"paris.museum":true,"pasadena.museum":true,"pharmacy.museum":true,"philadelphia.museum":true,"philadelphiaarea.museum":true,"philately.museum":true,"phoenix.museum":true,"photography.museum":true,"pilots.museum":true,"pittsburgh.museum":true,"planetarium.museum":true,"plantation.museum":true,"plants.museum":true,"plaza.museum":true,"portal.museum":true,"portland.museum":true,"portlligat.museum":true,"posts-and-telecommunications.museum":true,"preservation.museum":true,"presidio.museum":true,"press.museum":true,"project.museum":true,"public.museum":true,"pubol.museum":true,"quebec.museum":true,"railroad.museum":true,"railway.museum":true,"research.museum":true,"resistance.museum":true,"riodejaneiro.museum":true,"rochester.museum":true,"rockart.museum":true,"roma.museum":true,"russia.museum":true,"saintlouis.museum":true,"salem.museum":true,"salvadordali.museum":true,"salzburg.museum":true,"sandiego.museum":true,"sanfrancisco.museum":true,"santabarbara.museum":true,"santacruz.museum":true,"santafe.museum":true,"saskatchewan.museum":true,"satx.museum":true,"savannahga.museum":true,"schlesisches.museum":true,"schoenbrunn.museum":true,"schokoladen.museum":true,"school.museum":true,"schweiz.museum":true,"science.museum":true,"scienceandhistory.museum":true,"scienceandindustry.museum":true,"sciencecenter.museum":true,"sciencecenters.museum":true,"science-fiction.museum":true,"sciencehistory.museum":true,"sciences.museum":true,"sciencesnaturelles.museum":true,"scotland.museum":true,"seaport.museum":true,"settlement.museum":true,"settlers.museum":true,"shell.museum":true,"sherbrooke.museum":true,"sibenik.museum":true,"silk.museum":true,"ski.museum":true,"skole.museum":true,"society.museum":true,"sologne.museum":true,"soundandvision.museum":true,"southcarolina.museum":true,"southwest.museum":true,"space.museum":true,"spy.museum":true,"square.museum":true,"stadt.museum":true,"stalbans.museum":true,"starnberg.museum":true,"state.museum":true,"stateofdelaware.museum":true,"station.museum":true,"steam.museum":true,"steiermark.museum":true,"stjohn.museum":true,"stockholm.museum":true,"stpetersburg.museum":true,"stuttgart.museum":true,"suisse.museum":true,"surgeonshall.museum":true,"surrey.museum":true,"svizzera.museum":true,"sweden.museum":true,"sydney.museum":true,"tank.museum":true,"tcm.museum":true,"technology.museum":true,"telekommunikation.museum":true,"television.museum":true,"texas.museum":true,"textile.museum":true,"theater.museum":true,"time.museum":true,"timekeeping.museum":true,"topology.museum":true,"torino.museum":true,"touch.museum":true,"town.museum":true,"transport.museum":true,"tree.museum":true,"trolley.museum":true,"trust.museum":true,"trustee.museum":true,"uhren.museum":true,"ulm.museum":true,"undersea.museum":true,"university.museum":true,"usa.museum":true,"usantiques.museum":true,"usarts.museum":true,"uscountryestate.museum":true,"usculture.museum":true,"usdecorativearts.museum":true,"usgarden.museum":true,"ushistory.museum":true,"ushuaia.museum":true,"uslivinghistory.museum":true,"utah.museum":true,"uvic.museum":true,"valley.museum":true,"vantaa.museum":true,"versailles.museum":true,"viking.museum":true,"village.museum":true,"virginia.museum":true,"virtual.museum":true,"virtuel.museum":true,"vlaanderen.museum":true,"volkenkunde.museum":true,"wales.museum":true,"wallonie.museum":true,"war.museum":true,"washingtondc.museum":true,"watchandclock.museum":true,"watch-and-clock.museum":true,"western.museum":true,"westfalen.museum":true,"whaling.museum":true,"wildlife.museum":true,"williamsburg.museum":true,"windmill.museum":true,"workshop.museum":true,"york.museum":true,"yorkshire.museum":true,"yosemite.museum":true,"youth.museum":true,"zoological.museum":true,"zoology.museum":true,"xn--9dbhblg6di.museum":true,"xn--h1aegh.museum":true,"mv":true,"aero.mv":true,"biz.mv":true,"com.mv":true,"coop.mv":true,"edu.mv":true,"gov.mv":true,"info.mv":true,"int.mv":true,"mil.mv":true,"museum.mv":true,"name.mv":true,"net.mv":true,"org.mv":true,"pro.mv":true,"mw":true,"ac.mw":true,"biz.mw":true,"co.mw":true,"com.mw":true,"coop.mw":true,"edu.mw":true,"gov.mw":true,"int.mw":true,"museum.mw":true,"net.mw":true,"org.mw":true,"mx":true,"com.mx":true,"org.mx":true,"gob.mx":true,"edu.mx":true,"net.mx":true,"my":true,"com.my":true,"net.my":true,"org.my":true,"gov.my":true,"edu.my":true,"mil.my":true,"name.my":true,"*.mz":true,"teledata.mz":false,"na":true,"info.na":true,"pro.na":true,"name.na":true,"school.na":true,"or.na":true,"dr.na":true,"us.na":true,"mx.na":true,"ca.na":true,"in.na":true,"cc.na":true,"tv.na":true,"ws.na":true,"mobi.na":true,"co.na":true,"com.na":true,"org.na":true,"name":true,"nc":true,"asso.nc":true,"ne":true,"net":true,"nf":true,"com.nf":true,"net.nf":true,"per.nf":true,"rec.nf":true,"web.nf":true,"arts.nf":true,"firm.nf":true,"info.nf":true,"other.nf":true,"store.nf":true,"ng":true,"com.ng":true,"edu.ng":true,"name.ng":true,"net.ng":true,"org.ng":true,"sch.ng":true,"gov.ng":true,"mil.ng":true,"mobi.ng":true,"*.ni":true,"nl":true,"bv.nl":true,"no":true,"fhs.no":true,"vgs.no":true,"fylkesbibl.no":true,"folkebibl.no":true,"museum.no":true,"idrett.no":true,"priv.no":true,"mil.no":true,"stat.no":true,"dep.no":true,"kommune.no":true,"herad.no":true,"aa.no":true,"ah.no":true,"bu.no":true,"fm.no":true,"hl.no":true,"hm.no":true,"jan-mayen.no":true,"mr.no":true,"nl.no":true,"nt.no":true,"of.no":true,"ol.no":true,"oslo.no":true,"rl.no":true,"sf.no":true,"st.no":true,"svalbard.no":true,"tm.no":true,"tr.no":true,"va.no":true,"vf.no":true,"gs.aa.no":true,"gs.ah.no":true,"gs.bu.no":true,"gs.fm.no":true,"gs.hl.no":true,"gs.hm.no":true,"gs.jan-mayen.no":true,"gs.mr.no":true,"gs.nl.no":true,"gs.nt.no":true,"gs.of.no":true,"gs.ol.no":true,"gs.oslo.no":true,"gs.rl.no":true,"gs.sf.no":true,"gs.st.no":true,"gs.svalbard.no":true,"gs.tm.no":true,"gs.tr.no":true,"gs.va.no":true,"gs.vf.no":true,"akrehamn.no":true,"xn--krehamn-dxa.no":true,"algard.no":true,"xn--lgrd-poac.no":true,"arna.no":true,"brumunddal.no":true,"bryne.no":true,"bronnoysund.no":true,"xn--brnnysund-m8ac.no":true,"drobak.no":true,"xn--drbak-wua.no":true,"egersund.no":true,"fetsund.no":true,"floro.no":true,"xn--flor-jra.no":true,"fredrikstad.no":true,"hokksund.no":true,"honefoss.no":true,"xn--hnefoss-q1a.no":true,"jessheim.no":true,"jorpeland.no":true,"xn--jrpeland-54a.no":true,"kirkenes.no":true,"kopervik.no":true,"krokstadelva.no":true,"langevag.no":true,"xn--langevg-jxa.no":true,"leirvik.no":true,"mjondalen.no":true,"xn--mjndalen-64a.no":true,"mo-i-rana.no":true,"mosjoen.no":true,"xn--mosjen-eya.no":true,"nesoddtangen.no":true,"orkanger.no":true,"osoyro.no":true,"xn--osyro-wua.no":true,"raholt.no":true,"xn--rholt-mra.no":true,"sandnessjoen.no":true,"xn--sandnessjen-ogb.no":true,"skedsmokorset.no":true,"slattum.no":true,"spjelkavik.no":true,"stathelle.no":true,"stavern.no":true,"stjordalshalsen.no":true,"xn--stjrdalshalsen-sqb.no":true,"tananger.no":true,"tranby.no":true,"vossevangen.no":true,"afjord.no":true,"xn--fjord-lra.no":true,"agdenes.no":true,"al.no":true,"xn--l-1fa.no":true,"alesund.no":true,"xn--lesund-hua.no":true,"alstahaug.no":true,"alta.no":true,"xn--lt-liac.no":true,"alaheadju.no":true,"xn--laheadju-7ya.no":true,"alvdal.no":true,"amli.no":true,"xn--mli-tla.no":true,"amot.no":true,"xn--mot-tla.no":true,"andebu.no":true,"andoy.no":true,"xn--andy-ira.no":true,"andasuolo.no":true,"ardal.no":true,"xn--rdal-poa.no":true,"aremark.no":true,"arendal.no":true,"xn--s-1fa.no":true,"aseral.no":true,"xn--seral-lra.no":true,"asker.no":true,"askim.no":true,"askvoll.no":true,"askoy.no":true,"xn--asky-ira.no":true,"asnes.no":true,"xn--snes-poa.no":true,"audnedaln.no":true,"aukra.no":true,"aure.no":true,"aurland.no":true,"aurskog-holand.no":true,"xn--aurskog-hland-jnb.no":true,"austevoll.no":true,"austrheim.no":true,"averoy.no":true,"xn--avery-yua.no":true,"balestrand.no":true,"ballangen.no":true,"balat.no":true,"xn--blt-elab.no":true,"balsfjord.no":true,"bahccavuotna.no":true,"xn--bhccavuotna-k7a.no":true,"bamble.no":true,"bardu.no":true,"beardu.no":true,"beiarn.no":true,"bajddar.no":true,"xn--bjddar-pta.no":true,"baidar.no":true,"xn--bidr-5nac.no":true,"berg.no":true,"bergen.no":true,"berlevag.no":true,"xn--berlevg-jxa.no":true,"bearalvahki.no":true,"xn--bearalvhki-y4a.no":true,"bindal.no":true,"birkenes.no":true,"bjarkoy.no":true,"xn--bjarky-fya.no":true,"bjerkreim.no":true,"bjugn.no":true,"bodo.no":true,"xn--bod-2na.no":true,"badaddja.no":true,"xn--bdddj-mrabd.no":true,"budejju.no":true,"bokn.no":true,"bremanger.no":true,"bronnoy.no":true,"xn--brnny-wuac.no":true,"bygland.no":true,"bykle.no":true,"barum.no":true,"xn--brum-voa.no":true,"bo.telemark.no":true,"xn--b-5ga.telemark.no":true,"bo.nordland.no":true,"xn--b-5ga.nordland.no":true,"bievat.no":true,"xn--bievt-0qa.no":true,"bomlo.no":true,"xn--bmlo-gra.no":true,"batsfjord.no":true,"xn--btsfjord-9za.no":true,"bahcavuotna.no":true,"xn--bhcavuotna-s4a.no":true,"dovre.no":true,"drammen.no":true,"drangedal.no":true,"dyroy.no":true,"xn--dyry-ira.no":true,"donna.no":true,"xn--dnna-gra.no":true,"eid.no":true,"eidfjord.no":true,"eidsberg.no":true,"eidskog.no":true,"eidsvoll.no":true,"eigersund.no":true,"elverum.no":true,"enebakk.no":true,"engerdal.no":true,"etne.no":true,"etnedal.no":true,"evenes.no":true,"evenassi.no":true,"xn--eveni-0qa01ga.no":true,"evje-og-hornnes.no":true,"farsund.no":true,"fauske.no":true,"fuossko.no":true,"fuoisku.no":true,"fedje.no":true,"fet.no":true,"finnoy.no":true,"xn--finny-yua.no":true,"fitjar.no":true,"fjaler.no":true,"fjell.no":true,"flakstad.no":true,"flatanger.no":true,"flekkefjord.no":true,"flesberg.no":true,"flora.no":true,"fla.no":true,"xn--fl-zia.no":true,"folldal.no":true,"forsand.no":true,"fosnes.no":true,"frei.no":true,"frogn.no":true,"froland.no":true,"frosta.no":true,"frana.no":true,"xn--frna-woa.no":true,"froya.no":true,"xn--frya-hra.no":true,"fusa.no":true,"fyresdal.no":true,"forde.no":true,"xn--frde-gra.no":true,"gamvik.no":true,"gangaviika.no":true,"xn--ggaviika-8ya47h.no":true,"gaular.no":true,"gausdal.no":true,"gildeskal.no":true,"xn--gildeskl-g0a.no":true,"giske.no":true,"gjemnes.no":true,"gjerdrum.no":true,"gjerstad.no":true,"gjesdal.no":true,"gjovik.no":true,"xn--gjvik-wua.no":true,"gloppen.no":true,"gol.no":true,"gran.no":true,"grane.no":true,"granvin.no":true,"gratangen.no":true,"grimstad.no":true,"grong.no":true,"kraanghke.no":true,"xn--kranghke-b0a.no":true,"grue.no":true,"gulen.no":true,"hadsel.no":true,"halden.no":true,"halsa.no":true,"hamar.no":true,"hamaroy.no":true,"habmer.no":true,"xn--hbmer-xqa.no":true,"hapmir.no":true,"xn--hpmir-xqa.no":true,"hammerfest.no":true,"hammarfeasta.no":true,"xn--hmmrfeasta-s4ac.no":true,"haram.no":true,"hareid.no":true,"harstad.no":true,"hasvik.no":true,"aknoluokta.no":true,"xn--koluokta-7ya57h.no":true,"hattfjelldal.no":true,"aarborte.no":true,"haugesund.no":true,"hemne.no":true,"hemnes.no":true,"hemsedal.no":true,"heroy.more-og-romsdal.no":true,"xn--hery-ira.xn--mre-og-romsdal-qqb.no":true,"heroy.nordland.no":true,"xn--hery-ira.nordland.no":true,"hitra.no":true,"hjartdal.no":true,"hjelmeland.no":true,"hobol.no":true,"xn--hobl-ira.no":true,"hof.no":true,"hol.no":true,"hole.no":true,"holmestrand.no":true,"holtalen.no":true,"xn--holtlen-hxa.no":true,"hornindal.no":true,"horten.no":true,"hurdal.no":true,"hurum.no":true,"hvaler.no":true,"hyllestad.no":true,"hagebostad.no":true,"xn--hgebostad-g3a.no":true,"hoyanger.no":true,"xn--hyanger-q1a.no":true,"hoylandet.no":true,"xn--hylandet-54a.no":true,"ha.no":true,"xn--h-2fa.no":true,"ibestad.no":true,"inderoy.no":true,"xn--indery-fya.no":true,"iveland.no":true,"jevnaker.no":true,"jondal.no":true,"jolster.no":true,"xn--jlster-bya.no":true,"karasjok.no":true,"karasjohka.no":true,"xn--krjohka-hwab49j.no":true,"karlsoy.no":true,"galsa.no":true,"xn--gls-elac.no":true,"karmoy.no":true,"xn--karmy-yua.no":true,"kautokeino.no":true,"guovdageaidnu.no":true,"klepp.no":true,"klabu.no":true,"xn--klbu-woa.no":true,"kongsberg.no":true,"kongsvinger.no":true,"kragero.no":true,"xn--krager-gya.no":true,"kristiansand.no":true,"kristiansund.no":true,"krodsherad.no":true,"xn--krdsherad-m8a.no":true,"kvalsund.no":true,"rahkkeravju.no":true,"xn--rhkkervju-01af.no":true,"kvam.no":true,"kvinesdal.no":true,"kvinnherad.no":true,"kviteseid.no":true,"kvitsoy.no":true,"xn--kvitsy-fya.no":true,"kvafjord.no":true,"xn--kvfjord-nxa.no":true,"giehtavuoatna.no":true,"kvanangen.no":true,"xn--kvnangen-k0a.no":true,"navuotna.no":true,"xn--nvuotna-hwa.no":true,"kafjord.no":true,"xn--kfjord-iua.no":true,"gaivuotna.no":true,"xn--givuotna-8ya.no":true,"larvik.no":true,"lavangen.no":true,"lavagis.no":true,"loabat.no":true,"xn--loabt-0qa.no":true,"lebesby.no":true,"davvesiida.no":true,"leikanger.no":true,"leirfjord.no":true,"leka.no":true,"leksvik.no":true,"lenvik.no":true,"leangaviika.no":true,"xn--leagaviika-52b.no":true,"lesja.no":true,"levanger.no":true,"lier.no":true,"lierne.no":true,"lillehammer.no":true,"lillesand.no":true,"lindesnes.no":true,"lindas.no":true,"xn--linds-pra.no":true,"lom.no":true,"loppa.no":true,"lahppi.no":true,"xn--lhppi-xqa.no":true,"lund.no":true,"lunner.no":true,"luroy.no":true,"xn--lury-ira.no":true,"luster.no":true,"lyngdal.no":true,"lyngen.no":true,"ivgu.no":true,"lardal.no":true,"lerdal.no":true,"xn--lrdal-sra.no":true,"lodingen.no":true,"xn--ldingen-q1a.no":true,"lorenskog.no":true,"xn--lrenskog-54a.no":true,"loten.no":true,"xn--lten-gra.no":true,"malvik.no":true,"masoy.no":true,"xn--msy-ula0h.no":true,"muosat.no":true,"xn--muost-0qa.no":true,"mandal.no":true,"marker.no":true,"marnardal.no":true,"masfjorden.no":true,"meland.no":true,"meldal.no":true,"melhus.no":true,"meloy.no":true,"xn--mely-ira.no":true,"meraker.no":true,"xn--merker-kua.no":true,"moareke.no":true,"xn--moreke-jua.no":true,"midsund.no":true,"midtre-gauldal.no":true,"modalen.no":true,"modum.no":true,"molde.no":true,"moskenes.no":true,"moss.no":true,"mosvik.no":true,"malselv.no":true,"xn--mlselv-iua.no":true,"malatvuopmi.no":true,"xn--mlatvuopmi-s4a.no":true,"namdalseid.no":true,"aejrie.no":true,"namsos.no":true,"namsskogan.no":true,"naamesjevuemie.no":true,"xn--nmesjevuemie-tcba.no":true,"laakesvuemie.no":true,"nannestad.no":true,"narvik.no":true,"narviika.no":true,"naustdal.no":true,"nedre-eiker.no":true,"nes.akershus.no":true,"nes.buskerud.no":true,"nesna.no":true,"nesodden.no":true,"nesseby.no":true,"unjarga.no":true,"xn--unjrga-rta.no":true,"nesset.no":true,"nissedal.no":true,"nittedal.no":true,"nord-aurdal.no":true,"nord-fron.no":true,"nord-odal.no":true,"norddal.no":true,"nordkapp.no":true,"davvenjarga.no":true,"xn--davvenjrga-y4a.no":true,"nordre-land.no":true,"nordreisa.no":true,"raisa.no":true,"xn--risa-5na.no":true,"nore-og-uvdal.no":true,"notodden.no":true,"naroy.no":true,"xn--nry-yla5g.no":true,"notteroy.no":true,"xn--nttery-byae.no":true,"odda.no":true,"oksnes.no":true,"xn--ksnes-uua.no":true,"oppdal.no":true,"oppegard.no":true,"xn--oppegrd-ixa.no":true,"orkdal.no":true,"orland.no":true,"xn--rland-uua.no":true,"orskog.no":true,"xn--rskog-uua.no":true,"orsta.no":true,"xn--rsta-fra.no":true,"os.hedmark.no":true,"os.hordaland.no":true,"osen.no":true,"osteroy.no":true,"xn--ostery-fya.no":true,"ostre-toten.no":true,"xn--stre-toten-zcb.no":true,"overhalla.no":true,"ovre-eiker.no":true,"xn--vre-eiker-k8a.no":true,"oyer.no":true,"xn--yer-zna.no":true,"oygarden.no":true,"xn--ygarden-p1a.no":true,"oystre-slidre.no":true,"xn--ystre-slidre-ujb.no":true,"porsanger.no":true,"porsangu.no":true,"xn--porsgu-sta26f.no":true,"porsgrunn.no":true,"radoy.no":true,"xn--rady-ira.no":true,"rakkestad.no":true,"rana.no":true,"ruovat.no":true,"randaberg.no":true,"rauma.no":true,"rendalen.no":true,"rennebu.no":true,"rennesoy.no":true,"xn--rennesy-v1a.no":true,"rindal.no":true,"ringebu.no":true,"ringerike.no":true,"ringsaker.no":true,"rissa.no":true,"risor.no":true,"xn--risr-ira.no":true,"roan.no":true,"rollag.no":true,"rygge.no":true,"ralingen.no":true,"xn--rlingen-mxa.no":true,"rodoy.no":true,"xn--rdy-0nab.no":true,"romskog.no":true,"xn--rmskog-bya.no":true,"roros.no":true,"xn--rros-gra.no":true,"rost.no":true,"xn--rst-0na.no":true,"royken.no":true,"xn--ryken-vua.no":true,"royrvik.no":true,"xn--ryrvik-bya.no":true,"rade.no":true,"xn--rde-ula.no":true,"salangen.no":true,"siellak.no":true,"saltdal.no":true,"salat.no":true,"xn--slt-elab.no":true,"xn--slat-5na.no":true,"samnanger.no":true,"sande.more-og-romsdal.no":true,"sande.xn--mre-og-romsdal-qqb.no":true,"sande.vestfold.no":true,"sandefjord.no":true,"sandnes.no":true,"sandoy.no":true,"xn--sandy-yua.no":true,"sarpsborg.no":true,"sauda.no":true,"sauherad.no":true,"sel.no":true,"selbu.no":true,"selje.no":true,"seljord.no":true,"sigdal.no":true,"siljan.no":true,"sirdal.no":true,"skaun.no":true,"skedsmo.no":true,"ski.no":true,"skien.no":true,"skiptvet.no":true,"skjervoy.no":true,"xn--skjervy-v1a.no":true,"skierva.no":true,"xn--skierv-uta.no":true,"skjak.no":true,"xn--skjk-soa.no":true,"skodje.no":true,"skanland.no":true,"xn--sknland-fxa.no":true,"skanit.no":true,"xn--sknit-yqa.no":true,"smola.no":true,"xn--smla-hra.no":true,"snillfjord.no":true,"snasa.no":true,"xn--snsa-roa.no":true,"snoasa.no":true,"snaase.no":true,"xn--snase-nra.no":true,"sogndal.no":true,"sokndal.no":true,"sola.no":true,"solund.no":true,"songdalen.no":true,"sortland.no":true,"spydeberg.no":true,"stange.no":true,"stavanger.no":true,"steigen.no":true,"steinkjer.no":true,"stjordal.no":true,"xn--stjrdal-s1a.no":true,"stokke.no":true,"stor-elvdal.no":true,"stord.no":true,"stordal.no":true,"storfjord.no":true,"omasvuotna.no":true,"strand.no":true,"stranda.no":true,"stryn.no":true,"sula.no":true,"suldal.no":true,"sund.no":true,"sunndal.no":true,"surnadal.no":true,"sveio.no":true,"svelvik.no":true,"sykkylven.no":true,"sogne.no":true,"xn--sgne-gra.no":true,"somna.no":true,"xn--smna-gra.no":true,"sondre-land.no":true,"xn--sndre-land-0cb.no":true,"sor-aurdal.no":true,"xn--sr-aurdal-l8a.no":true,"sor-fron.no":true,"xn--sr-fron-q1a.no":true,"sor-odal.no":true,"xn--sr-odal-q1a.no":true,"sor-varanger.no":true,"xn--sr-varanger-ggb.no":true,"matta-varjjat.no":true,"xn--mtta-vrjjat-k7af.no":true,"sorfold.no":true,"xn--srfold-bya.no":true,"sorreisa.no":true,"xn--srreisa-q1a.no":true,"sorum.no":true,"xn--srum-gra.no":true,"tana.no":true,"deatnu.no":true,"time.no":true,"tingvoll.no":true,"tinn.no":true,"tjeldsund.no":true,"dielddanuorri.no":true,"tjome.no":true,"xn--tjme-hra.no":true,"tokke.no":true,"tolga.no":true,"torsken.no":true,"tranoy.no":true,"xn--trany-yua.no":true,"tromso.no":true,"xn--troms-zua.no":true,"tromsa.no":true,"romsa.no":true,"trondheim.no":true,"troandin.no":true,"trysil.no":true,"trana.no":true,"xn--trna-woa.no":true,"trogstad.no":true,"xn--trgstad-r1a.no":true,"tvedestrand.no":true,"tydal.no":true,"tynset.no":true,"tysfjord.no":true,"divtasvuodna.no":true,"divttasvuotna.no":true,"tysnes.no":true,"tysvar.no":true,"xn--tysvr-vra.no":true,"tonsberg.no":true,"xn--tnsberg-q1a.no":true,"ullensaker.no":true,"ullensvang.no":true,"ulvik.no":true,"utsira.no":true,"vadso.no":true,"xn--vads-jra.no":true,"cahcesuolo.no":true,"xn--hcesuolo-7ya35b.no":true,"vaksdal.no":true,"valle.no":true,"vang.no":true,"vanylven.no":true,"vardo.no":true,"xn--vard-jra.no":true,"varggat.no":true,"xn--vrggt-xqad.no":true,"vefsn.no":true,"vaapste.no":true,"vega.no":true,"vegarshei.no":true,"xn--vegrshei-c0a.no":true,"vennesla.no":true,"verdal.no":true,"verran.no":true,"vestby.no":true,"vestnes.no":true,"vestre-slidre.no":true,"vestre-toten.no":true,"vestvagoy.no":true,"xn--vestvgy-ixa6o.no":true,"vevelstad.no":true,"vik.no":true,"vikna.no":true,"vindafjord.no":true,"volda.no":true,"voss.no":true,"varoy.no":true,"xn--vry-yla5g.no":true,"vagan.no":true,"xn--vgan-qoa.no":true,"voagat.no":true,"vagsoy.no":true,"xn--vgsy-qoa0j.no":true,"vaga.no":true,"xn--vg-yiab.no":true,"valer.ostfold.no":true,"xn--vler-qoa.xn--stfold-9xa.no":true,"valer.hedmark.no":true,"xn--vler-qoa.hedmark.no":true,"*.np":true,"nr":true,"biz.nr":true,"info.nr":true,"gov.nr":true,"edu.nr":true,"org.nr":true,"net.nr":true,"com.nr":true,"nu":true,"nz":true,"ac.nz":true,"co.nz":true,"cri.nz":true,"geek.nz":true,"gen.nz":true,"govt.nz":true,"health.nz":true,"iwi.nz":true,"kiwi.nz":true,"maori.nz":true,"mil.nz":true,"xn--mori-qsa.nz":true,"net.nz":true,"org.nz":true,"parliament.nz":true,"school.nz":true,"om":true,"co.om":true,"com.om":true,"edu.om":true,"gov.om":true,"med.om":true,"museum.om":true,"net.om":true,"org.om":true,"pro.om":true,"org":true,"pa":true,"ac.pa":true,"gob.pa":true,"com.pa":true,"org.pa":true,"sld.pa":true,"edu.pa":true,"net.pa":true,"ing.pa":true,"abo.pa":true,"med.pa":true,"nom.pa":true,"pe":true,"edu.pe":true,"gob.pe":true,"nom.pe":true,"mil.pe":true,"org.pe":true,"com.pe":true,"net.pe":true,"pf":true,"com.pf":true,"org.pf":true,"edu.pf":true,"*.pg":true,"ph":true,"com.ph":true,"net.ph":true,"org.ph":true,"gov.ph":true,"edu.ph":true,"ngo.ph":true,"mil.ph":true,"i.ph":true,"pk":true,"com.pk":true,"net.pk":true,"edu.pk":true,"org.pk":true,"fam.pk":true,"biz.pk":true,"web.pk":true,"gov.pk":true,"gob.pk":true,"gok.pk":true,"gon.pk":true,"gop.pk":true,"gos.pk":true,"info.pk":true,"pl":true,"com.pl":true,"net.pl":true,"org.pl":true,"info.pl":true,"waw.pl":true,"gov.pl":true,"aid.pl":true,"agro.pl":true,"atm.pl":true,"auto.pl":true,"biz.pl":true,"edu.pl":true,"gmina.pl":true,"gsm.pl":true,"mail.pl":true,"miasta.pl":true,"media.pl":true,"mil.pl":true,"nieruchomosci.pl":true,"nom.pl":true,"pc.pl":true,"powiat.pl":true,"priv.pl":true,"realestate.pl":true,"rel.pl":true,"sex.pl":true,"shop.pl":true,"sklep.pl":true,"sos.pl":true,"szkola.pl":true,"targi.pl":true,"tm.pl":true,"tourism.pl":true,"travel.pl":true,"turystyka.pl":true,"uw.gov.pl":true,"um.gov.pl":true,"ug.gov.pl":true,"upow.gov.pl":true,"starostwo.gov.pl":true,"so.gov.pl":true,"sr.gov.pl":true,"po.gov.pl":true,"pa.gov.pl":true,"augustow.pl":true,"babia-gora.pl":true,"bedzin.pl":true,"beskidy.pl":true,"bialowieza.pl":true,"bialystok.pl":true,"bielawa.pl":true,"bieszczady.pl":true,"boleslawiec.pl":true,"bydgoszcz.pl":true,"bytom.pl":true,"cieszyn.pl":true,"czeladz.pl":true,"czest.pl":true,"dlugoleka.pl":true,"elblag.pl":true,"elk.pl":true,"glogow.pl":true,"gniezno.pl":true,"gorlice.pl":true,"grajewo.pl":true,"ilawa.pl":true,"jaworzno.pl":true,"jelenia-gora.pl":true,"jgora.pl":true,"kalisz.pl":true,"kazimierz-dolny.pl":true,"karpacz.pl":true,"kartuzy.pl":true,"kaszuby.pl":true,"katowice.pl":true,"kepno.pl":true,"ketrzyn.pl":true,"klodzko.pl":true,"kobierzyce.pl":true,"kolobrzeg.pl":true,"konin.pl":true,"konskowola.pl":true,"kutno.pl":true,"lapy.pl":true,"lebork.pl":true,"legnica.pl":true,"lezajsk.pl":true,"limanowa.pl":true,"lomza.pl":true,"lowicz.pl":true,"lubin.pl":true,"lukow.pl":true,"malbork.pl":true,"malopolska.pl":true,"mazowsze.pl":true,"mazury.pl":true,"mielec.pl":true,"mielno.pl":true,"mragowo.pl":true,"naklo.pl":true,"nowaruda.pl":true,"nysa.pl":true,"olawa.pl":true,"olecko.pl":true,"olkusz.pl":true,"olsztyn.pl":true,"opoczno.pl":true,"opole.pl":true,"ostroda.pl":true,"ostroleka.pl":true,"ostrowiec.pl":true,"ostrowwlkp.pl":true,"pila.pl":true,"pisz.pl":true,"podhale.pl":true,"podlasie.pl":true,"polkowice.pl":true,"pomorze.pl":true,"pomorskie.pl":true,"prochowice.pl":true,"pruszkow.pl":true,"przeworsk.pl":true,"pulawy.pl":true,"radom.pl":true,"rawa-maz.pl":true,"rybnik.pl":true,"rzeszow.pl":true,"sanok.pl":true,"sejny.pl":true,"slask.pl":true,"slupsk.pl":true,"sosnowiec.pl":true,"stalowa-wola.pl":true,"skoczow.pl":true,"starachowice.pl":true,"stargard.pl":true,"suwalki.pl":true,"swidnica.pl":true,"swiebodzin.pl":true,"swinoujscie.pl":true,"szczecin.pl":true,"szczytno.pl":true,"tarnobrzeg.pl":true,"tgory.pl":true,"turek.pl":true,"tychy.pl":true,"ustka.pl":true,"walbrzych.pl":true,"warmia.pl":true,"warszawa.pl":true,"wegrow.pl":true,"wielun.pl":true,"wlocl.pl":true,"wloclawek.pl":true,"wodzislaw.pl":true,"wolomin.pl":true,"wroclaw.pl":true,"zachpomor.pl":true,"zagan.pl":true,"zarow.pl":true,"zgora.pl":true,"zgorzelec.pl":true,"pm":true,"pn":true,"gov.pn":true,"co.pn":true,"org.pn":true,"edu.pn":true,"net.pn":true,"post":true,"pr":true,"com.pr":true,"net.pr":true,"org.pr":true,"gov.pr":true,"edu.pr":true,"isla.pr":true,"pro.pr":true,"biz.pr":true,"info.pr":true,"name.pr":true,"est.pr":true,"prof.pr":true,"ac.pr":true,"pro":true,"aca.pro":true,"bar.pro":true,"cpa.pro":true,"jur.pro":true,"law.pro":true,"med.pro":true,"eng.pro":true,"ps":true,"edu.ps":true,"gov.ps":true,"sec.ps":true,"plo.ps":true,"com.ps":true,"org.ps":true,"net.ps":true,"pt":true,"net.pt":true,"gov.pt":true,"org.pt":true,"edu.pt":true,"int.pt":true,"publ.pt":true,"com.pt":true,"nome.pt":true,"pw":true,"co.pw":true,"ne.pw":true,"or.pw":true,"ed.pw":true,"go.pw":true,"belau.pw":true,"py":true,"com.py":true,"coop.py":true,"edu.py":true,"gov.py":true,"mil.py":true,"net.py":true,"org.py":true,"qa":true,"com.qa":true,"edu.qa":true,"gov.qa":true,"mil.qa":true,"name.qa":true,"net.qa":true,"org.qa":true,"sch.qa":true,"re":true,"com.re":true,"asso.re":true,"nom.re":true,"ro":true,"com.ro":true,"org.ro":true,"tm.ro":true,"nt.ro":true,"nom.ro":true,"info.ro":true,"rec.ro":true,"arts.ro":true,"firm.ro":true,"store.ro":true,"www.ro":true,"rs":true,"co.rs":true,"org.rs":true,"edu.rs":true,"ac.rs":true,"gov.rs":true,"in.rs":true,"ru":true,"ac.ru":true,"com.ru":true,"edu.ru":true,"int.ru":true,"net.ru":true,"org.ru":true,"pp.ru":true,"adygeya.ru":true,"altai.ru":true,"amur.ru":true,"arkhangelsk.ru":true,"astrakhan.ru":true,"bashkiria.ru":true,"belgorod.ru":true,"bir.ru":true,"bryansk.ru":true,"buryatia.ru":true,"cbg.ru":true,"chel.ru":true,"chelyabinsk.ru":true,"chita.ru":true,"chukotka.ru":true,"chuvashia.ru":true,"dagestan.ru":true,"dudinka.ru":true,"e-burg.ru":true,"grozny.ru":true,"irkutsk.ru":true,"ivanovo.ru":true,"izhevsk.ru":true,"jar.ru":true,"joshkar-ola.ru":true,"kalmykia.ru":true,"kaluga.ru":true,"kamchatka.ru":true,"karelia.ru":true,"kazan.ru":true,"kchr.ru":true,"kemerovo.ru":true,"khabarovsk.ru":true,"khakassia.ru":true,"khv.ru":true,"kirov.ru":true,"koenig.ru":true,"komi.ru":true,"kostroma.ru":true,"krasnoyarsk.ru":true,"kuban.ru":true,"kurgan.ru":true,"kursk.ru":true,"lipetsk.ru":true,"magadan.ru":true,"mari.ru":true,"mari-el.ru":true,"marine.ru":true,"mordovia.ru":true,"msk.ru":true,"murmansk.ru":true,"nalchik.ru":true,"nnov.ru":true,"nov.ru":true,"novosibirsk.ru":true,"nsk.ru":true,"omsk.ru":true,"orenburg.ru":true,"oryol.ru":true,"palana.ru":true,"penza.ru":true,"perm.ru":true,"ptz.ru":true,"rnd.ru":true,"ryazan.ru":true,"sakhalin.ru":true,"samara.ru":true,"saratov.ru":true,"simbirsk.ru":true,"smolensk.ru":true,"spb.ru":true,"stavropol.ru":true,"stv.ru":true,"surgut.ru":true,"tambov.ru":true,"tatarstan.ru":true,"tom.ru":true,"tomsk.ru":true,"tsaritsyn.ru":true,"tsk.ru":true,"tula.ru":true,"tuva.ru":true,"tver.ru":true,"tyumen.ru":true,"udm.ru":true,"udmurtia.ru":true,"ulan-ude.ru":true,"vladikavkaz.ru":true,"vladimir.ru":true,"vladivostok.ru":true,"volgograd.ru":true,"vologda.ru":true,"voronezh.ru":true,"vrn.ru":true,"vyatka.ru":true,"yakutia.ru":true,"yamal.ru":true,"yaroslavl.ru":true,"yekaterinburg.ru":true,"yuzhno-sakhalinsk.ru":true,"amursk.ru":true,"baikal.ru":true,"cmw.ru":true,"fareast.ru":true,"jamal.ru":true,"kms.ru":true,"k-uralsk.ru":true,"kustanai.ru":true,"kuzbass.ru":true,"magnitka.ru":true,"mytis.ru":true,"nakhodka.ru":true,"nkz.ru":true,"norilsk.ru":true,"oskol.ru":true,"pyatigorsk.ru":true,"rubtsovsk.ru":true,"snz.ru":true,"syzran.ru":true,"vdonsk.ru":true,"zgrad.ru":true,"gov.ru":true,"mil.ru":true,"test.ru":true,"rw":true,"gov.rw":true,"net.rw":true,"edu.rw":true,"ac.rw":true,"com.rw":true,"co.rw":true,"int.rw":true,"mil.rw":true,"gouv.rw":true,"sa":true,"com.sa":true,"net.sa":true,"org.sa":true,"gov.sa":true,"med.sa":true,"pub.sa":true,"edu.sa":true,"sch.sa":true,"sb":true,"com.sb":true,"edu.sb":true,"gov.sb":true,"net.sb":true,"org.sb":true,"sc":true,"com.sc":true,"gov.sc":true,"net.sc":true,"org.sc":true,"edu.sc":true,"sd":true,"com.sd":true,"net.sd":true,"org.sd":true,"edu.sd":true,"med.sd":true,"tv.sd":true,"gov.sd":true,"info.sd":true,"se":true,"a.se":true,"ac.se":true,"b.se":true,"bd.se":true,"brand.se":true,"c.se":true,"d.se":true,"e.se":true,"f.se":true,"fh.se":true,"fhsk.se":true,"fhv.se":true,"g.se":true,"h.se":true,"i.se":true,"k.se":true,"komforb.se":true,"kommunalforbund.se":true,"komvux.se":true,"l.se":true,"lanbib.se":true,"m.se":true,"n.se":true,"naturbruksgymn.se":true,"o.se":true,"org.se":true,"p.se":true,"parti.se":true,"pp.se":true,"press.se":true,"r.se":true,"s.se":true,"t.se":true,"tm.se":true,"u.se":true,"w.se":true,"x.se":true,"y.se":true,"z.se":true,"sg":true,"com.sg":true,"net.sg":true,"org.sg":true,"gov.sg":true,"edu.sg":true,"per.sg":true,"sh":true,"com.sh":true,"net.sh":true,"gov.sh":true,"org.sh":true,"mil.sh":true,"si":true,"sj":true,"sk":true,"sl":true,"com.sl":true,"net.sl":true,"edu.sl":true,"gov.sl":true,"org.sl":true,"sm":true,"sn":true,"art.sn":true,"com.sn":true,"edu.sn":true,"gouv.sn":true,"org.sn":true,"perso.sn":true,"univ.sn":true,"so":true,"com.so":true,"net.so":true,"org.so":true,"sr":true,"st":true,"co.st":true,"com.st":true,"consulado.st":true,"edu.st":true,"embaixada.st":true,"gov.st":true,"mil.st":true,"net.st":true,"org.st":true,"principe.st":true,"saotome.st":true,"store.st":true,"su":true,"adygeya.su":true,"arkhangelsk.su":true,"balashov.su":true,"bashkiria.su":true,"bryansk.su":true,"dagestan.su":true,"grozny.su":true,"ivanovo.su":true,"kalmykia.su":true,"kaluga.su":true,"karelia.su":true,"khakassia.su":true,"krasnodar.su":true,"kurgan.su":true,"lenug.su":true,"mordovia.su":true,"msk.su":true,"murmansk.su":true,"nalchik.su":true,"nov.su":true,"obninsk.su":true,"penza.su":true,"pokrovsk.su":true,"sochi.su":true,"spb.su":true,"togliatti.su":true,"troitsk.su":true,"tula.su":true,"tuva.su":true,"vladikavkaz.su":true,"vladimir.su":true,"vologda.su":true,"sv":true,"com.sv":true,"edu.sv":true,"gob.sv":true,"org.sv":true,"red.sv":true,"sx":true,"gov.sx":true,"sy":true,"edu.sy":true,"gov.sy":true,"net.sy":true,"mil.sy":true,"com.sy":true,"org.sy":true,"sz":true,"co.sz":true,"ac.sz":true,"org.sz":true,"tc":true,"td":true,"tel":true,"tf":true,"tg":true,"th":true,"ac.th":true,"co.th":true,"go.th":true,"in.th":true,"mi.th":true,"net.th":true,"or.th":true,"tj":true,"ac.tj":true,"biz.tj":true,"co.tj":true,"com.tj":true,"edu.tj":true,"go.tj":true,"gov.tj":true,"int.tj":true,"mil.tj":true,"name.tj":true,"net.tj":true,"nic.tj":true,"org.tj":true,"test.tj":true,"web.tj":true,"tk":true,"tl":true,"gov.tl":true,"tm":true,"com.tm":true,"co.tm":true,"org.tm":true,"net.tm":true,"nom.tm":true,"gov.tm":true,"mil.tm":true,"edu.tm":true,"tn":true,"com.tn":true,"ens.tn":true,"fin.tn":true,"gov.tn":true,"ind.tn":true,"intl.tn":true,"nat.tn":true,"net.tn":true,"org.tn":true,"info.tn":true,"perso.tn":true,"tourism.tn":true,"edunet.tn":true,"rnrt.tn":true,"rns.tn":true,"rnu.tn":true,"mincom.tn":true,"agrinet.tn":true,"defense.tn":true,"turen.tn":true,"to":true,"com.to":true,"gov.to":true,"net.to":true,"org.to":true,"edu.to":true,"mil.to":true,"tp":true,"tr":true,"com.tr":true,"info.tr":true,"biz.tr":true,"net.tr":true,"org.tr":true,"web.tr":true,"gen.tr":true,"tv.tr":true,"av.tr":true,"dr.tr":true,"bbs.tr":true,"name.tr":true,"tel.tr":true,"gov.tr":true,"bel.tr":true,"pol.tr":true,"mil.tr":true,"k12.tr":true,"edu.tr":true,"kep.tr":true,"nc.tr":true,"gov.nc.tr":true,"travel":true,"tt":true,"co.tt":true,"com.tt":true,"org.tt":true,"net.tt":true,"biz.tt":true,"info.tt":true,"pro.tt":true,"int.tt":true,"coop.tt":true,"jobs.tt":true,"mobi.tt":true,"travel.tt":true,"museum.tt":true,"aero.tt":true,"name.tt":true,"gov.tt":true,"edu.tt":true,"tv":true,"tw":true,"edu.tw":true,"gov.tw":true,"mil.tw":true,"com.tw":true,"net.tw":true,"org.tw":true,"idv.tw":true,"game.tw":true,"ebiz.tw":true,"club.tw":true,"xn--zf0ao64a.tw":true,"xn--uc0atv.tw":true,"xn--czrw28b.tw":true,"tz":true,"ac.tz":true,"co.tz":true,"go.tz":true,"hotel.tz":true,"info.tz":true,"me.tz":true,"mil.tz":true,"mobi.tz":true,"ne.tz":true,"or.tz":true,"sc.tz":true,"tv.tz":true,"ua":true,"com.ua":true,"edu.ua":true,"gov.ua":true,"in.ua":true,"net.ua":true,"org.ua":true,"cherkassy.ua":true,"cherkasy.ua":true,"chernigov.ua":true,"chernihiv.ua":true,"chernivtsi.ua":true,"chernovtsy.ua":true,"ck.ua":true,"cn.ua":true,"cr.ua":true,"crimea.ua":true,"cv.ua":true,"dn.ua":true,"dnepropetrovsk.ua":true,"dnipropetrovsk.ua":true,"dominic.ua":true,"donetsk.ua":true,"dp.ua":true,"if.ua":true,"ivano-frankivsk.ua":true,"kh.ua":true,"kharkiv.ua":true,"kharkov.ua":true,"kherson.ua":true,"khmelnitskiy.ua":true,"khmelnytskyi.ua":true,"kiev.ua":true,"kirovograd.ua":true,"km.ua":true,"kr.ua":true,"krym.ua":true,"ks.ua":true,"kv.ua":true,"kyiv.ua":true,"lg.ua":true,"lt.ua":true,"lugansk.ua":true,"lutsk.ua":true,"lv.ua":true,"lviv.ua":true,"mk.ua":true,"mykolaiv.ua":true,"nikolaev.ua":true,"od.ua":true,"odesa.ua":true,"odessa.ua":true,"pl.ua":true,"poltava.ua":true,"rivne.ua":true,"rovno.ua":true,"rv.ua":true,"sb.ua":true,"sebastopol.ua":true,"sevastopol.ua":true,"sm.ua":true,"sumy.ua":true,"te.ua":true,"ternopil.ua":true,"uz.ua":true,"uzhgorod.ua":true,"vinnica.ua":true,"vinnytsia.ua":true,"vn.ua":true,"volyn.ua":true,"yalta.ua":true,"zaporizhzhe.ua":true,"zaporizhzhia.ua":true,"zhitomir.ua":true,"zhytomyr.ua":true,"zp.ua":true,"zt.ua":true,"co.ua":true,"pp.ua":true,"ug":true,"co.ug":true,"or.ug":true,"ac.ug":true,"sc.ug":true,"go.ug":true,"ne.ug":true,"com.ug":true,"org.ug":true,"uk":true,"ac.uk":true,"co.uk":true,"gov.uk":true,"ltd.uk":true,"me.uk":true,"net.uk":true,"nhs.uk":true,"org.uk":true,"plc.uk":true,"police.uk":true,"*.sch.uk":true,"us":true,"dni.us":true,"fed.us":true,"isa.us":true,"kids.us":true,"nsn.us":true,"ak.us":true,"al.us":true,"ar.us":true,"as.us":true,"az.us":true,"ca.us":true,"co.us":true,"ct.us":true,"dc.us":true,"de.us":true,"fl.us":true,"ga.us":true,"gu.us":true,"hi.us":true,"ia.us":true,"id.us":true,"il.us":true,"in.us":true,"ks.us":true,"ky.us":true,"la.us":true,"ma.us":true,"md.us":true,"me.us":true,"mi.us":true,"mn.us":true,"mo.us":true,"ms.us":true,"mt.us":true,"nc.us":true,"nd.us":true,"ne.us":true,"nh.us":true,"nj.us":true,"nm.us":true,"nv.us":true,"ny.us":true,"oh.us":true,"ok.us":true,"or.us":true,"pa.us":true,"pr.us":true,"ri.us":true,"sc.us":true,"sd.us":true,"tn.us":true,"tx.us":true,"ut.us":true,"vi.us":true,"vt.us":true,"va.us":true,"wa.us":true,"wi.us":true,"wv.us":true,"wy.us":true,"k12.ak.us":true,"k12.al.us":true,"k12.ar.us":true,"k12.as.us":true,"k12.az.us":true,"k12.ca.us":true,"k12.co.us":true,"k12.ct.us":true,"k12.dc.us":true,"k12.de.us":true,"k12.fl.us":true,"k12.ga.us":true,"k12.gu.us":true,"k12.ia.us":true,"k12.id.us":true,"k12.il.us":true,"k12.in.us":true,"k12.ks.us":true,"k12.ky.us":true,"k12.la.us":true,"k12.ma.us":true,"k12.md.us":true,"k12.me.us":true,"k12.mi.us":true,"k12.mn.us":true,"k12.mo.us":true,"k12.ms.us":true,"k12.mt.us":true,"k12.nc.us":true,"k12.ne.us":true,"k12.nh.us":true,"k12.nj.us":true,"k12.nm.us":true,"k12.nv.us":true,"k12.ny.us":true,"k12.oh.us":true,"k12.ok.us":true,"k12.or.us":true,"k12.pa.us":true,"k12.pr.us":true,"k12.ri.us":true,"k12.sc.us":true,"k12.tn.us":true,"k12.tx.us":true,"k12.ut.us":true,"k12.vi.us":true,"k12.vt.us":true,"k12.va.us":true,"k12.wa.us":true,"k12.wi.us":true,"k12.wy.us":true,"cc.ak.us":true,"cc.al.us":true,"cc.ar.us":true,"cc.as.us":true,"cc.az.us":true,"cc.ca.us":true,"cc.co.us":true,"cc.ct.us":true,"cc.dc.us":true,"cc.de.us":true,"cc.fl.us":true,"cc.ga.us":true,"cc.gu.us":true,"cc.hi.us":true,"cc.ia.us":true,"cc.id.us":true,"cc.il.us":true,"cc.in.us":true,"cc.ks.us":true,"cc.ky.us":true,"cc.la.us":true,"cc.ma.us":true,"cc.md.us":true,"cc.me.us":true,"cc.mi.us":true,"cc.mn.us":true,"cc.mo.us":true,"cc.ms.us":true,"cc.mt.us":true,"cc.nc.us":true,"cc.nd.us":true,"cc.ne.us":true,"cc.nh.us":true,"cc.nj.us":true,"cc.nm.us":true,"cc.nv.us":true,"cc.ny.us":true,"cc.oh.us":true,"cc.ok.us":true,"cc.or.us":true,"cc.pa.us":true,"cc.pr.us":true,"cc.ri.us":true,"cc.sc.us":true,"cc.sd.us":true,"cc.tn.us":true,"cc.tx.us":true,"cc.ut.us":true,"cc.vi.us":true,"cc.vt.us":true,"cc.va.us":true,"cc.wa.us":true,"cc.wi.us":true,"cc.wv.us":true,"cc.wy.us":true,"lib.ak.us":true,"lib.al.us":true,"lib.ar.us":true,"lib.as.us":true,"lib.az.us":true,"lib.ca.us":true,"lib.co.us":true,"lib.ct.us":true,"lib.dc.us":true,"lib.de.us":true,"lib.fl.us":true,"lib.ga.us":true,"lib.gu.us":true,"lib.hi.us":true,"lib.ia.us":true,"lib.id.us":true,"lib.il.us":true,"lib.in.us":true,"lib.ks.us":true,"lib.ky.us":true,"lib.la.us":true,"lib.ma.us":true,"lib.md.us":true,"lib.me.us":true,"lib.mi.us":true,"lib.mn.us":true,"lib.mo.us":true,"lib.ms.us":true,"lib.mt.us":true,"lib.nc.us":true,"lib.nd.us":true,"lib.ne.us":true,"lib.nh.us":true,"lib.nj.us":true,"lib.nm.us":true,"lib.nv.us":true,"lib.ny.us":true,"lib.oh.us":true,"lib.ok.us":true,"lib.or.us":true,"lib.pa.us":true,"lib.pr.us":true,"lib.ri.us":true,"lib.sc.us":true,"lib.sd.us":true,"lib.tn.us":true,"lib.tx.us":true,"lib.ut.us":true,"lib.vi.us":true,"lib.vt.us":true,"lib.va.us":true,"lib.wa.us":true,"lib.wi.us":true,"lib.wy.us":true,"pvt.k12.ma.us":true,"chtr.k12.ma.us":true,"paroch.k12.ma.us":true,"uy":true,"com.uy":true,"edu.uy":true,"gub.uy":true,"mil.uy":true,"net.uy":true,"org.uy":true,"uz":true,"co.uz":true,"com.uz":true,"net.uz":true,"org.uz":true,"va":true,"vc":true,"com.vc":true,"net.vc":true,"org.vc":true,"gov.vc":true,"mil.vc":true,"edu.vc":true,"ve":true,"arts.ve":true,"co.ve":true,"com.ve":true,"e12.ve":true,"edu.ve":true,"firm.ve":true,"gob.ve":true,"gov.ve":true,"info.ve":true,"int.ve":true,"mil.ve":true,"net.ve":true,"org.ve":true,"rec.ve":true,"store.ve":true,"tec.ve":true,"web.ve":true,"vg":true,"vi":true,"co.vi":true,"com.vi":true,"k12.vi":true,"net.vi":true,"org.vi":true,"vn":true,"com.vn":true,"net.vn":true,"org.vn":true,"edu.vn":true,"gov.vn":true,"int.vn":true,"ac.vn":true,"biz.vn":true,"info.vn":true,"name.vn":true,"pro.vn":true,"health.vn":true,"vu":true,"com.vu":true,"edu.vu":true,"net.vu":true,"org.vu":true,"wf":true,"ws":true,"com.ws":true,"net.ws":true,"org.ws":true,"gov.ws":true,"edu.ws":true,"yt":true,"xn--mgbaam7a8h":true,"xn--54b7fta0cc":true,"xn--fiqs8s":true,"xn--fiqz9s":true,"xn--lgbbat1ad8j":true,"xn--wgbh1c":true,"xn--node":true,"xn--j6w193g":true,"xn--h2brj9c":true,"xn--mgbbh1a71e":true,"xn--fpcrj9c3d":true,"xn--gecrj9c":true,"xn--s9brj9c":true,"xn--45brj9c":true,"xn--xkc2dl3a5ee0h":true,"xn--mgba3a4f16a":true,"xn--mgba3a4fra":true,"xn--mgbayh7gpa":true,"xn--3e0b707e":true,"xn--80ao21a":true,"xn--fzc2c9e2c":true,"xn--xkc2al3hye2a":true,"xn--mgbc0a9azcg":true,"xn--l1acc":true,"xn--mgbx4cd0ab":true,"xn--mgb9awbf":true,"xn--ygbi2ammx":true,"xn--90a3ac":true,"xn--o1ac.xn--90a3ac":true,"xn--c1avg.xn--90a3ac":true,"xn--90azh.xn--90a3ac":true,"xn--d1at.xn--90a3ac":true,"xn--o1ach.xn--90a3ac":true,"xn--80au.xn--90a3ac":true,"xn--p1ai":true,"xn--wgbl6a":true,"xn--mgberp4a5d4ar":true,"xn--mgberp4a5d4a87g":true,"xn--mgbqly7c0a67fbc":true,"xn--mgbqly7cvafr":true,"xn--ogbpf8fl":true,"xn--mgbtf8fl":true,"xn--yfro4i67o":true,"xn--clchc0ea0b2g2a9gcd":true,"xn--o3cw4h":true,"xn--pgbs0dh":true,"xn--kpry57d":true,"xn--kprw13d":true,"xn--nnx388a":true,"xn--j1amh":true,"xn--mgb2ddes":true,"xxx":true,"*.ye":true,"*.za":true,"*.zm":true,"*.zw":true,"aaa":true,"abb":true,"abbott":true,"abogado":true,"academy":true,"accenture":true,"accountant":true,"accountants":true,"aco":true,"active":true,"actor":true,"ads":true,"adult":true,"aeg":true,"afl":true,"africa":true,"africamagic":true,"agency":true,"aig":true,"airforce":true,"airtel":true,"alibaba":true,"alipay":true,"allfinanz":true,"alsace":true,"amsterdam":true,"analytics":true,"android":true,"anquan":true,"apartments":true,"aquarelle":true,"aramco":true,"archi":true,"army":true,"arte":true,"associates":true,"attorney":true,"auction":true,"audio":true,"author":true,"auto":true,"autos":true,"avianca":true,"axa":true,"azure":true,"baidu":true,"band":true,"bank":true,"bar":true,"barcelona":true,"barclaycard":true,"barclays":true,"bargains":true,"bauhaus":true,"bayern":true,"bbc":true,"bbva":true,"bcg":true,"bcn":true,"beer":true,"bentley":true,"berlin":true,"best":true,"bharti":true,"bible":true,"bid":true,"bike":true,"bing":true,"bingo":true,"bio":true,"black":true,"blackfriday":true,"bloomberg":true,"blue":true,"bms":true,"bmw":true,"bnl":true,"bnpparibas":true,"boats":true,"bom":true,"bond":true,"boo":true,"boots":true,"bot":true,"boutique":true,"bradesco":true,"bridgestone":true,"broadway":true,"broker":true,"brother":true,"brussels":true,"budapest":true,"build":true,"builders":true,"business":true,"buy":true,"buzz":true,"bzh":true,"cab":true,"cafe":true,"cal":true,"call":true,"camera":true,"camp":true,"cancerresearch":true,"canon":true,"capetown":true,"capital":true,"car":true,"caravan":true,"cards":true,"care":true,"career":true,"careers":true,"cars":true,"cartier":true,"casa":true,"cash":true,"casino":true,"catering":true,"cba":true,"cbn":true,"center":true,"ceo":true,"cern":true,"cfa":true,"cfd":true,"channel":true,"chat":true,"cheap":true,"chloe":true,"christmas":true,"chrome":true,"church":true,"cipriani":true,"circle":true,"cisco":true,"citic":true,"city":true,"cityeats":true,"claims":true,"cleaning":true,"click":true,"clinic":true,"clothing":true,"club":true,"coach":true,"codes":true,"coffee":true,"college":true,"cologne":true,"commbank":true,"community":true,"company":true,"computer":true,"comsec":true,"condos":true,"construction":true,"consulting":true,"contact":true,"contractors":true,"cooking":true,"cool":true,"corsica":true,"country":true,"coupon":true,"coupons":true,"courses":true,"credit":true,"creditcard":true,"creditunion":true,"cricket":true,"crown":true,"crs":true,"cruises":true,"csc":true,"cuisinella":true,"cymru":true,"cyou":true,"dabur":true,"dad":true,"dance":true,"date":true,"dating":true,"datsun":true,"day":true,"dclk":true,"dealer":true,"deals":true,"degree":true,"delivery":true,"dell":true,"delta":true,"democrat":true,"dental":true,"dentist":true,"desi":true,"design":true,"dev":true,"diamonds":true,"diet":true,"digital":true,"direct":true,"directory":true,"discount":true,"dnp":true,"docs":true,"dog":true,"doha":true,"domains":true,"doosan":true,"download":true,"drive":true,"dstv":true,"dubai":true,"durban":true,"dvag":true,"earth":true,"eat":true,"edeka":true,"education":true,"email":true,"emerck":true,"energy":true,"engineer":true,"engineering":true,"enterprises":true,"epson":true,"equipment":true,"erni":true,"esq":true,"estate":true,"eurovision":true,"eus":true,"events":true,"everbank":true,"exchange":true,"expert":true,"exposed":true,"express":true,"fage":true,"fail":true,"fairwinds":true,"faith":true,"family":true,"fan":true,"fans":true,"farm":true,"fashion":true,"fast":true,"feedback":true,"ferrero":true,"film":true,"final":true,"finance":true,"financial":true,"firestone":true,"firmdale":true,"fish":true,"fishing":true,"fit":true,"fitness":true,"flickr":true,"flights":true,"florist":true,"flowers":true,"flsmidth":true,"fly":true,"foo":true,"football":true,"ford":true,"forex":true,"forsale":true,"forum":true,"foundation":true,"frl":true,"frogans":true,"frontier":true,"fund":true,"furniture":true,"futbol":true,"fyi":true,"gal":true,"gallery":true,"gallup":true,"garden":true,"gbiz":true,"gdn":true,"gea":true,"gent":true,"genting":true,"ggee":true,"gift":true,"gifts":true,"gives":true,"giving":true,"glass":true,"gle":true,"global":true,"globo":true,"gmail":true,"gmo":true,"gmx":true,"gold":true,"goldpoint":true,"golf":true,"goo":true,"goog":true,"google":true,"gop":true,"got":true,"gotv":true,"graphics":true,"gratis":true,"green":true,"gripe":true,"group":true,"gucci":true,"guge":true,"guide":true,"guitars":true,"guru":true,"hamburg":true,"hangout":true,"haus":true,"hdfcbank":true,"health":true,"healthcare":true,"help":true,"helsinki":true,"here":true,"hermes":true,"hiphop":true,"hitachi":true,"hiv":true,"hockey":true,"holdings":true,"holiday":true,"homedepot":true,"homes":true,"honda":true,"horse":true,"host":true,"hosting":true,"hoteles":true,"hotmail":true,"house":true,"how":true,"hsbc":true,"htc":true,"ibm":true,"icbc":true,"ice":true,"icu":true,"ifm":true,"iinet":true,"immo":true,"immobilien":true,"industries":true,"infiniti":true,"ing":true,"ink":true,"institute":true,"insurance":true,"insure":true,"international":true,"investments":true,"ipiranga":true,"irish":true,"iselect":true,"ist":true,"istanbul":true,"itau":true,"iwc":true,"jaguar":true,"java":true,"jcb":true,"jetzt":true,"jewelry":true,"jio":true,"jlc":true,"jll":true,"jmp":true,"joburg":true,"jot":true,"joy":true,"jprs":true,"juegos":true,"kaufen":true,"kddi":true,"kfh":true,"kim":true,"kinder":true,"kitchen":true,"kiwi":true,"koeln":true,"komatsu":true,"kpn":true,"krd":true,"kred":true,"kyknet":true,"kyoto":true,"lacaixa":true,"lancaster":true,"land":true,"landrover":true,"lasalle":true,"lat":true,"latrobe":true,"law":true,"lawyer":true,"lds":true,"lease":true,"leclerc":true,"legal":true,"lgbt":true,"liaison":true,"lidl":true,"life":true,"lifeinsurance":true,"lifestyle":true,"lighting":true,"like":true,"limited":true,"limo":true,"lincoln":true,"linde":true,"link":true,"live":true,"lixil":true,"loan":true,"loans":true,"lol":true,"london":true,"lotte":true,"lotto":true,"love":true,"ltd":true,"ltda":true,"lupin":true,"luxe":true,"luxury":true,"madrid":true,"maif":true,"maison":true,"makeup":true,"man":true,"management":true,"mango":true,"market":true,"marketing":true,"markets":true,"marriott":true,"mba":true,"media":true,"meet":true,"melbourne":true,"meme":true,"memorial":true,"men":true,"menu":true,"meo":true,"miami":true,"microsoft":true,"mini":true,"mma":true,"mnet":true,"mobily":true,"moda":true,"moe":true,"moi":true,"monash":true,"money":true,"montblanc":true,"mormon":true,"mortgage":true,"moscow":true,"motorcycles":true,"mov":true,"movie":true,"movistar":true,"mtn":true,"mtpc":true,"mtr":true,"multichoice":true,"mutual":true,"mzansimagic":true,"nadex":true,"nagoya":true,"naspers":true,"natura":true,"navy":true,"nec":true,"netbank":true,"network":true,"neustar":true,"new":true,"news":true,"nexus":true,"ngo":true,"nhk":true,"nico":true,"ninja":true,"nissan":true,"nokia":true,"norton":true,"nowruz":true,"nra":true,"nrw":true,"ntt":true,"nyc":true,"obi":true,"office":true,"okinawa":true,"omega":true,"one":true,"ong":true,"onl":true,"online":true,"ooo":true,"oracle":true,"orange":true,"organic":true,"orientexpress":true,"osaka":true,"otsuka":true,"ovh":true,"page":true,"pamperedchef":true,"panerai":true,"paris":true,"pars":true,"partners":true,"parts":true,"party":true,"passagens":true,"payu":true,"pharmacy":true,"philips":true,"photo":true,"photography":true,"photos":true,"physio":true,"piaget":true,"pics":true,"pictet":true,"pictures":true,"pid":true,"pin":true,"pink":true,"pizza":true,"place":true,"play":true,"plumbing":true,"plus":true,"pohl":true,"poker":true,"porn":true,"praxi":true,"press":true,"prod":true,"productions":true,"prof":true,"promo":true,"properties":true,"property":true,"pub":true,"qpon":true,"quebec":true,"quest":true,"racing":true,"read":true,"realtor":true,"realty":true,"recipes":true,"red":true,"redstone":true,"redumbrella":true,"rehab":true,"reise":true,"reisen":true,"reit":true,"reliance":true,"ren":true,"rent":true,"rentals":true,"repair":true,"report":true,"republican":true,"rest":true,"restaurant":true,"review":true,"reviews":true,"rich":true,"ricoh":true,"ril":true,"rio":true,"rip":true,"rocher":true,"rocks":true,"rodeo":true,"room":true,"rsvp":true,"ruhr":true,"run":true,"rwe":true,"ryukyu":true,"saarland":true,"safe":true,"safety":true,"sakura":true,"sale":true,"salon":true,"samsung":true,"sandvik":true,"sandvikcoromant":true,"sanofi":true,"sap":true,"sapo":true,"sarl":true,"sas":true,"saxo":true,"sbi":true,"sbs":true,"sca":true,"scb":true,"schmidt":true,"scholarships":true,"school":true,"schule":true,"schwarz":true,"science":true,"scor":true,"scot":true,"seat":true,"seek":true,"sener":true,"services":true,"sew":true,"sex":true,"sexy":true,"sharp":true,"shia":true,"shiksha":true,"shoes":true,"shouji":true,"show":true,"shriram":true,"sina":true,"singles":true,"site":true,"skin":true,"sky":true,"skype":true,"smile":true,"sncf":true,"soccer":true,"social":true,"software":true,"sohu":true,"solar":true,"solutions":true,"song":true,"sony":true,"soy":true,"space":true,"spiegel":true,"spot":true,"spreadbetting":true,"stada":true,"star":true,"starhub":true,"statebank":true,"statoil":true,"stc":true,"stcgroup":true,"stockholm":true,"storage":true,"studio":true,"study":true,"style":true,"sucks":true,"supersport":true,"supplies":true,"supply":true,"support":true,"surf":true,"surgery":true,"suzuki":true,"swatch":true,"swiss":true,"sydney":true,"symantec":true,"systems":true,"tab":true,"taipei":true,"taobao":true,"tatamotors":true,"tatar":true,"tattoo":true,"tax":true,"taxi":true,"tci":true,"team":true,"tech":true,"technology":true,"telecity":true,"telefonica":true,"temasek":true,"tennis":true,"thd":true,"theater":true,"tickets":true,"tienda":true,"tiffany":true,"tips":true,"tires":true,"tirol":true,"tmall":true,"today":true,"tokyo":true,"tools":true,"top":true,"toray":true,"toshiba":true,"tours":true,"town":true,"toys":true,"trade":true,"trading":true,"training":true,"travelers":true,"travelersinsurance":true,"trust":true,"trv":true,"tui":true,"tunes":true,"tushu":true,"tvs":true,"ubs":true,"university":true,"uno":true,"uol":true,"vacations":true,"vana":true,"vegas":true,"ventures":true,"versicherung":true,"vet":true,"viajes":true,"video":true,"viking":true,"villas":true,"vip":true,"virgin":true,"vision":true,"vista":true,"vistaprint":true,"viva":true,"vlaanderen":true,"vodka":true,"vote":true,"voting":true,"voto":true,"voyage":true,"vuelos":true,"wales":true,"walter":true,"wang":true,"wanggou":true,"watch":true,"watches":true,"weather":true,"weatherchannel":true,"webcam":true,"website":true,"wed":true,"wedding":true,"weibo":true,"weir":true,"whoswho":true,"wien":true,"wiki":true,"williamhill":true,"win":true,"windows":true,"wme":true,"work":true,"works":true,"world":true,"wtc":true,"wtf":true,"xbox":true,"xerox":true,"xihuan":true,"xin":true,"xn--11b4c3d":true,"xn--1ck2e1b":true,"xn--1qqw23a":true,"xn--30rr7y":true,"xn--3bst00m":true,"xn--3ds443g":true,"xn--3pxu8k":true,"xn--42c2d9a":true,"xn--45q11c":true,"xn--4gbrim":true,"xn--55qw42g":true,"xn--55qx5d":true,"xn--5tzm5g":true,"xn--6frz82g":true,"xn--6qq986b3xl":true,"xn--80adxhks":true,"xn--80asehdb":true,"xn--80aswg":true,"xn--8y0a063a":true,"xn--9dbq2a":true,"xn--9et52u":true,"xn--9krt00a":true,"xn--b4w605ferd":true,"xn--bck1b9a5dre4c":true,"xn--c1avg":true,"xn--c2br7g":true,"xn--cck2b3b":true,"xn--cg4bki":true,"xn--czr694b":true,"xn--czrs0t":true,"xn--czru2d":true,"xn--d1acj3b":true,"xn--eckvdtc9d":true,"xn--efvy88h":true,"xn--estv75g":true,"xn--fhbei":true,"xn--fiq228c5hs":true,"xn--fiq64b":true,"xn--fjq720a":true,"xn--flw351e":true,"xn--g2xx48c":true,"xn--gckr3f0f":true,"xn--hxt814e":true,"xn--i1b6b1a6a2e":true,"xn--imr513n":true,"xn--io0a7i":true,"xn--j1aef":true,"xn--jlq61u9w7b":true,"xn--jvr189m":true,"xn--kcrx77d1x4a":true,"xn--kpu716f":true,"xn--kput3i":true,"xn--mgba3a3ejt":true,"xn--mgbab2bd":true,"xn--mgbb9fbpob":true,"xn--mgbt3dhd":true,"xn--mk1bu44c":true,"xn--mxtq1m":true,"xn--ngbc5azd":true,"xn--ngbe9e0a":true,"xn--nqv7f":true,"xn--nqv7fs00ema":true,"xn--nyqy26a":true,"xn--p1acf":true,"xn--pbt977c":true,"xn--pssy2u":true,"xn--q9jyb4c":true,"xn--qcka1pmc":true,"xn--rhqv96g":true,"xn--rovu88b":true,"xn--ses554g":true,"xn--t60b56a":true,"xn--tckwe":true,"xn--unup4y":true,"xn--vermgensberater-ctb":true,"xn--vermgensberatung-pwb":true,"xn--vhquv":true,"xn--vuq861b":true,"xn--xhq521b":true,"xn--zfr164b":true,"xyz":true,"yachts":true,"yahoo":true,"yamaxun":true,"yandex":true,"yodobashi":true,"yoga":true,"yokohama":true,"youtube":true,"yun":true,"zara":true,"zero":true,"zip":true,"zone":true,"zuerich":true,"cloudfront.net":true,"ap-northeast-1.compute.amazonaws.com":true,"ap-southeast-1.compute.amazonaws.com":true,"ap-southeast-2.compute.amazonaws.com":true,"cn-north-1.compute.amazonaws.cn":true,"compute.amazonaws.cn":true,"compute.amazonaws.com":true,"compute-1.amazonaws.com":true,"eu-west-1.compute.amazonaws.com":true,"eu-central-1.compute.amazonaws.com":true,"sa-east-1.compute.amazonaws.com":true,"us-east-1.amazonaws.com":true,"us-gov-west-1.compute.amazonaws.com":true,"us-west-1.compute.amazonaws.com":true,"us-west-2.compute.amazonaws.com":true,"z-1.compute-1.amazonaws.com":true,"z-2.compute-1.amazonaws.com":true,"elasticbeanstalk.com":true,"elb.amazonaws.com":true,"s3.amazonaws.com":true,"s3-us-west-2.amazonaws.com":true,"s3-us-west-1.amazonaws.com":true,"s3-eu-west-1.amazonaws.com":true,"s3-ap-southeast-1.amazonaws.com":true,"s3-ap-southeast-2.amazonaws.com":true,"s3-ap-northeast-1.amazonaws.com":true,"s3-sa-east-1.amazonaws.com":true,"s3-us-gov-west-1.amazonaws.com":true,"s3-fips-us-gov-west-1.amazonaws.com":true,"s3-website-us-east-1.amazonaws.com":true,"s3-website-us-west-2.amazonaws.com":true,"s3-website-us-west-1.amazonaws.com":true,"s3-website-eu-west-1.amazonaws.com":true,"s3-website-ap-southeast-1.amazonaws.com":true,"s3-website-ap-southeast-2.amazonaws.com":true,"s3-website-ap-northeast-1.amazonaws.com":true,"s3-website-sa-east-1.amazonaws.com":true,"s3-website-us-gov-west-1.amazonaws.com":true,"betainabox.com":true,"ae.org":true,"ar.com":true,"br.com":true,"cn.com":true,"com.de":true,"com.se":true,"de.com":true,"eu.com":true,"gb.com":true,"gb.net":true,"hu.com":true,"hu.net":true,"jp.net":true,"jpn.com":true,"kr.com":true,"mex.com":true,"no.com":true,"qc.com":true,"ru.com":true,"sa.com":true,"se.com":true,"se.net":true,"uk.com":true,"uk.net":true,"us.com":true,"uy.com":true,"za.bz":true,"za.com":true,"africa.com":true,"gr.com":true,"in.net":true,"us.org":true,"co.com":true,"c.la":true,"cloudcontrolled.com":true,"cloudcontrolapp.com":true,"co.ca":true,"co.nl":true,"co.no":true,"*.platform.sh":true,"cupcake.is":true,"dreamhosters.com":true,"dyndns-at-home.com":true,"dyndns-at-work.com":true,"dyndns-blog.com":true,"dyndns-free.com":true,"dyndns-home.com":true,"dyndns-ip.com":true,"dyndns-mail.com":true,"dyndns-office.com":true,"dyndns-pics.com":true,"dyndns-remote.com":true,"dyndns-server.com":true,"dyndns-web.com":true,"dyndns-wiki.com":true,"dyndns-work.com":true,"dyndns.biz":true,"dyndns.info":true,"dyndns.org":true,"dyndns.tv":true,"at-band-camp.net":true,"ath.cx":true,"barrel-of-knowledge.info":true,"barrell-of-knowledge.info":true,"better-than.tv":true,"blogdns.com":true,"blogdns.net":true,"blogdns.org":true,"blogsite.org":true,"boldlygoingnowhere.org":true,"broke-it.net":true,"buyshouses.net":true,"cechire.com":true,"dnsalias.com":true,"dnsalias.net":true,"dnsalias.org":true,"dnsdojo.com":true,"dnsdojo.net":true,"dnsdojo.org":true,"does-it.net":true,"doesntexist.com":true,"doesntexist.org":true,"dontexist.com":true,"dontexist.net":true,"dontexist.org":true,"doomdns.com":true,"doomdns.org":true,"dvrdns.org":true,"dyn-o-saur.com":true,"dynalias.com":true,"dynalias.net":true,"dynalias.org":true,"dynathome.net":true,"dyndns.ws":true,"endofinternet.net":true,"endofinternet.org":true,"endoftheinternet.org":true,"est-a-la-maison.com":true,"est-a-la-masion.com":true,"est-le-patron.com":true,"est-mon-blogueur.com":true,"for-better.biz":true,"for-more.biz":true,"for-our.info":true,"for-some.biz":true,"for-the.biz":true,"forgot.her.name":true,"forgot.his.name":true,"from-ak.com":true,"from-al.com":true,"from-ar.com":true,"from-az.net":true,"from-ca.com":true,"from-co.net":true,"from-ct.com":true,"from-dc.com":true,"from-de.com":true,"from-fl.com":true,"from-ga.com":true,"from-hi.com":true,"from-ia.com":true,"from-id.com":true,"from-il.com":true,"from-in.com":true,"from-ks.com":true,"from-ky.com":true,"from-la.net":true,"from-ma.com":true,"from-md.com":true,"from-me.org":true,"from-mi.com":true,"from-mn.com":true,"from-mo.com":true,"from-ms.com":true,"from-mt.com":true,"from-nc.com":true,"from-nd.com":true,"from-ne.com":true,"from-nh.com":true,"from-nj.com":true,"from-nm.com":true,"from-nv.com":true,"from-ny.net":true,"from-oh.com":true,"from-ok.com":true,"from-or.com":true,"from-pa.com":true,"from-pr.com":true,"from-ri.com":true,"from-sc.com":true,"from-sd.com":true,"from-tn.com":true,"from-tx.com":true,"from-ut.com":true,"from-va.com":true,"from-vt.com":true,"from-wa.com":true,"from-wi.com":true,"from-wv.com":true,"from-wy.com":true,"ftpaccess.cc":true,"fuettertdasnetz.de":true,"game-host.org":true,"game-server.cc":true,"getmyip.com":true,"gets-it.net":true,"go.dyndns.org":true,"gotdns.com":true,"gotdns.org":true,"groks-the.info":true,"groks-this.info":true,"ham-radio-op.net":true,"here-for-more.info":true,"hobby-site.com":true,"hobby-site.org":true,"home.dyndns.org":true,"homedns.org":true,"homeftp.net":true,"homeftp.org":true,"homeip.net":true,"homelinux.com":true,"homelinux.net":true,"homelinux.org":true,"homeunix.com":true,"homeunix.net":true,"homeunix.org":true,"iamallama.com":true,"in-the-band.net":true,"is-a-anarchist.com":true,"is-a-blogger.com":true,"is-a-bookkeeper.com":true,"is-a-bruinsfan.org":true,"is-a-bulls-fan.com":true,"is-a-candidate.org":true,"is-a-caterer.com":true,"is-a-celticsfan.org":true,"is-a-chef.com":true,"is-a-chef.net":true,"is-a-chef.org":true,"is-a-conservative.com":true,"is-a-cpa.com":true,"is-a-cubicle-slave.com":true,"is-a-democrat.com":true,"is-a-designer.com":true,"is-a-doctor.com":true,"is-a-financialadvisor.com":true,"is-a-geek.com":true,"is-a-geek.net":true,"is-a-geek.org":true,"is-a-green.com":true,"is-a-guru.com":true,"is-a-hard-worker.com":true,"is-a-hunter.com":true,"is-a-knight.org":true,"is-a-landscaper.com":true,"is-a-lawyer.com":true,"is-a-liberal.com":true,"is-a-libertarian.com":true,"is-a-linux-user.org":true,"is-a-llama.com":true,"is-a-musician.com":true,"is-a-nascarfan.com":true,"is-a-nurse.com":true,"is-a-painter.com":true,"is-a-patsfan.org":true,"is-a-personaltrainer.com":true,"is-a-photographer.com":true,"is-a-player.com":true,"is-a-republican.com":true,"is-a-rockstar.com":true,"is-a-socialist.com":true,"is-a-soxfan.org":true,"is-a-student.com":true,"is-a-teacher.com":true,"is-a-techie.com":true,"is-a-therapist.com":true,"is-an-accountant.com":true,"is-an-actor.com":true,"is-an-actress.com":true,"is-an-anarchist.com":true,"is-an-artist.com":true,"is-an-engineer.com":true,"is-an-entertainer.com":true,"is-by.us":true,"is-certified.com":true,"is-found.org":true,"is-gone.com":true,"is-into-anime.com":true,"is-into-cars.com":true,"is-into-cartoons.com":true,"is-into-games.com":true,"is-leet.com":true,"is-lost.org":true,"is-not-certified.com":true,"is-saved.org":true,"is-slick.com":true,"is-uberleet.com":true,"is-very-bad.org":true,"is-very-evil.org":true,"is-very-good.org":true,"is-very-nice.org":true,"is-very-sweet.org":true,"is-with-theband.com":true,"isa-geek.com":true,"isa-geek.net":true,"isa-geek.org":true,"isa-hockeynut.com":true,"issmarterthanyou.com":true,"isteingeek.de":true,"istmein.de":true,"kicks-ass.net":true,"kicks-ass.org":true,"knowsitall.info":true,"land-4-sale.us":true,"lebtimnetz.de":true,"leitungsen.de":true,"likes-pie.com":true,"likescandy.com":true,"merseine.nu":true,"mine.nu":true,"misconfused.org":true,"mypets.ws":true,"myphotos.cc":true,"neat-url.com":true,"office-on-the.net":true,"on-the-web.tv":true,"podzone.net":true,"podzone.org":true,"readmyblog.org":true,"saves-the-whales.com":true,"scrapper-site.net":true,"scrapping.cc":true,"selfip.biz":true,"selfip.com":true,"selfip.info":true,"selfip.net":true,"selfip.org":true,"sells-for-less.com":true,"sells-for-u.com":true,"sells-it.net":true,"sellsyourhome.org":true,"servebbs.com":true,"servebbs.net":true,"servebbs.org":true,"serveftp.net":true,"serveftp.org":true,"servegame.org":true,"shacknet.nu":true,"simple-url.com":true,"space-to-rent.com":true,"stuff-4-sale.org":true,"stuff-4-sale.us":true,"teaches-yoga.com":true,"thruhere.net":true,"traeumtgerade.de":true,"webhop.biz":true,"webhop.info":true,"webhop.net":true,"webhop.org":true,"worse-than.tv":true,"writesthisblog.com":true,"a.ssl.fastly.net":true,"b.ssl.fastly.net":true,"global.ssl.fastly.net":true,"a.prod.fastly.net":true,"global.prod.fastly.net":true,"firebaseapp.com":true,"flynnhub.com":true,"service.gov.uk":true,"github.io":true,"githubusercontent.com":true,"ro.com":true,"appspot.com":true,"blogspot.ae":true,"blogspot.be":true,"blogspot.bj":true,"blogspot.ca":true,"blogspot.cf":true,"blogspot.ch":true,"blogspot.co.at":true,"blogspot.co.il":true,"blogspot.co.nz":true,"blogspot.co.uk":true,"blogspot.com":true,"blogspot.com.ar":true,"blogspot.com.au":true,"blogspot.com.br":true,"blogspot.com.es":true,"blogspot.com.tr":true,"blogspot.cv":true,"blogspot.cz":true,"blogspot.de":true,"blogspot.dk":true,"blogspot.fi":true,"blogspot.fr":true,"blogspot.gr":true,"blogspot.hk":true,"blogspot.hu":true,"blogspot.ie":true,"blogspot.in":true,"blogspot.it":true,"blogspot.jp":true,"blogspot.kr":true,"blogspot.mr":true,"blogspot.mx":true,"blogspot.nl":true,"blogspot.no":true,"blogspot.pt":true,"blogspot.re":true,"blogspot.ro":true,"blogspot.ru":true,"blogspot.se":true,"blogspot.sg":true,"blogspot.sk":true,"blogspot.td":true,"blogspot.tw":true,"codespot.com":true,"googleapis.com":true,"googlecode.com":true,"pagespeedmobilizer.com":true,"withgoogle.com":true,"herokuapp.com":true,"herokussl.com":true,"iki.fi":true,"biz.at":true,"info.at":true,"co.pl":true,"azurewebsites.net":true,"azure-mobile.net":true,"cloudapp.net":true,"nfshost.com":true,"nyc.mn":true,"nid.io":true,"operaunite.com":true,"outsystemscloud.com":true,"art.pl":true,"gliwice.pl":true,"krakow.pl":true,"poznan.pl":true,"wroc.pl":true,"zakopane.pl":true,"priv.at":true,"rhcloud.com":true,"sinaapp.com":true,"vipsinaapp.com":true,"1kapp.com":true,"gda.pl":true,"gdansk.pl":true,"gdynia.pl":true,"med.pl":true,"sopot.pl":true,"hk.com":true,"hk.org":true,"ltd.hk":true,"inc.hk":true,"yolasite.com":true,"za.net":true,"za.org":true});
 
// END of automatically generated file
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/store.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tough-cookie/lib/store.js

Statements: 60% (9 / 15)      Branches: 100% (0 / 0)      Functions: 14.29% (1 / 7)      Lines: 60% (9 / 15)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                  1   1         1   1       1       1       1           1       1        
/*!
 * Copyright (c) 2015, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Salesforce.com nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
'use strict';
/*jshint unused:false */
 
function Store() {
}
exports.Store = Store;
 
// Stores may be synchronous, but are still required to use a
// Continuation-Passing Style API.  The CookieJar itself will expose a "*Sync"
// API that converts from synchronous-callbacks to imperative style.
Store.prototype.synchronous = false;
 
Store.prototype.findCookie = function(domain, path, key, cb) {
  throw new Error('findCookie is not implemented');
};
 
Store.prototype.findCookies = function(domain, path, cb) {
  throw new Error('findCookies is not implemented');
};
 
Store.prototype.putCookie = function(cookie, cb) {
  throw new Error('putCookie is not implemented');
};
 
Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
  // recommended default implementation:
  // return this.putCookie(newCookie, cb);
  throw new Error('updateCookie is not implemented');
};
 
Store.prototype.removeCookie = function(domain, path, key, cb) {
  throw new Error('removeCookie is not implemented');
};
 
Store.prototype.removeCookies = function removeCookies(domain, path, cb) {
  throw new Error('removeCookies is not implemented');
};
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tunnel-agent/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tunnel-agent/

Statements: 19.4% (26 / 134)      Branches: 5.88% (2 / 34)      Functions: 0% (0 / 23)      Lines: 19.55% (26 / 133)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tunnel-agent/
File Statements Branches Functions Lines
index.js 19.4% (26 / 134) 5.88% (2 / 34) 0% (0 / 23) 19.55% (26 / 133)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tunnel-agent/index.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/request/node_modules/tunnel-agent/index.js

Statements: 19.4% (26 / 134)      Branches: 5.88% (2 / 34)      Functions: 0% (0 / 23)      Lines: 19.55% (26 / 133)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238    1                 1 1 1 1     1           1             1           1               1                                             1   1                                                 1       1                 1                                                   1         1             1                                   1                     1                               1                           1                                 1 1                     1   1    
'use strict'
 
var net = require('net')
  , tls = require('tls')
  , http = require('http')
  , https = require('https')
  , events = require('events')
  , assert = require('assert')
  , util = require('util')
  ;
 
exports.httpOverHttp = httpOverHttp
exports.httpsOverHttp = httpsOverHttp
exports.httpOverHttps = httpOverHttps
exports.httpsOverHttps = httpsOverHttps
 
 
function httpOverHttp(options) {
  var agent = new TunnelingAgent(options)
  agent.request = http.request
  return agent
}
 
function httpsOverHttp(options) {
  var agent = new TunnelingAgent(options)
  agent.request = http.request
  agent.createSocket = createSecureSocket
  return agent
}
 
function httpOverHttps(options) {
  var agent = new TunnelingAgent(options)
  agent.request = https.request
  return agent
}
 
function httpsOverHttps(options) {
  var agent = new TunnelingAgent(options)
  agent.request = https.request
  agent.createSocket = createSecureSocket
  return agent
}
 
 
function TunnelingAgent(options) {
  var self = this
  self.options = options || {}
  self.proxyOptions = self.options.proxy || {}
  self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
  self.requests = []
  self.sockets = []
 
  self.on('free', function onFree(socket, host, port) {
    for (var i = 0, len = self.requests.length; i < len; ++i) {
      var pending = self.requests[i]
      if (pending.host === host && pending.port === port) {
        // Detect the request to connect same origin server,
        // reuse the connection.
        self.requests.splice(i, 1)
        pending.request.onSocket(socket)
        return
      }
    }
    socket.destroy()
    self.removeSocket(socket)
  })
}
util.inherits(TunnelingAgent, events.EventEmitter)
 
TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
  var self = this
 
   // Legacy API: addRequest(req, host, port, path)
  if (typeof options === 'string') {
    options = {
      host: options,
      port: arguments[2],
      path: arguments[3]
    };
  }
 
  if (self.sockets.length >= this.maxSockets) {
    // We are over limit so we'll add it to the queue.
    self.requests.push({host: host, port: port, request: req})
    return
  }
 
  // If we are under maxSockets create a new one.
  self.createSocket({host: options.host, port: options.port, request: req}, function(socket) {
    socket.on('free', onFree)
    socket.on('close', onCloseOrRemove)
    socket.on('agentRemove', onCloseOrRemove)
    req.onSocket(socket)
 
    function onFree() {
      self.emit('free', socket, options.host, options.port)
    }
 
    function onCloseOrRemove(err) {
      self.removeSocket()
      socket.removeListener('free', onFree)
      socket.removeListener('close', onCloseOrRemove)
      socket.removeListener('agentRemove', onCloseOrRemove)
    }
  })
}
 
TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
  var self = this
  var placeholder = {}
  self.sockets.push(placeholder)
 
  var connectOptions = mergeOptions({}, self.proxyOptions, 
    { method: 'CONNECT'
    , path: options.host + ':' + options.port
    , agent: false
    }
  )
  if (connectOptions.proxyAuth) {
    connectOptions.headers = connectOptions.headers || {}
    connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
        new Buffer(connectOptions.proxyAuth).toString('base64')
  }
 
  debug('making CONNECT request')
  var connectReq = self.request(connectOptions)
  connectReq.useChunkedEncodingByDefault = false // for v0.6
  connectReq.once('response', onResponse) // for v0.6
  connectReq.once('upgrade', onUpgrade)   // for v0.6
  connectReq.once('connect', onConnect)   // for v0.7 or later
  connectReq.once('error', onError)
  connectReq.end()
 
  function onResponse(res) {
    // Very hacky. This is necessary to avoid http-parser leaks.
    res.upgrade = true
  }
 
  function onUpgrade(res, socket, head) {
    // Hacky.
    process.nextTick(function() {
      onConnect(res, socket, head)
    })
  }
 
  function onConnect(res, socket, head) {
    connectReq.removeAllListeners()
    socket.removeAllListeners()
 
    if (res.statusCode === 200) {
      assert.equal(head.length, 0)
      debug('tunneling connection has established')
      self.sockets[self.sockets.indexOf(placeholder)] = socket
      cb(socket)
    } else {
      debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
      var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
      error.code = 'ECONNRESET'
      options.request.emit('error', error)
      self.removeSocket(placeholder)
    }
  }
 
  function onError(cause) {
    connectReq.removeAllListeners()
 
    debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
    var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
    error.code = 'ECONNRESET'
    options.request.emit('error', error)
    self.removeSocket(placeholder)
  }
}
 
TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
  var pos = this.sockets.indexOf(socket)
  if (pos === -1) return
  
  this.sockets.splice(pos, 1)
 
  var pending = this.requests.shift()
  if (pending) {
    // If we have pending requests and a socket gets closed a new one
    // needs to be created to take over in the pool for the one that closed.
    this.createSocket(pending, function(socket) {
      pending.request.onSocket(socket)
    })
  }
}
 
function createSecureSocket(options, cb) {
  var self = this
  TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
    // 0 is dummy port for v0.6
    var secureSocket = tls.connect(0, mergeOptions({}, self.options, 
      { servername: options.host
      , socket: socket
      }
    ))
    cb(secureSocket)
  })
}
 
 
function mergeOptions(target) {
  for (var i = 1, len = arguments.length; i < len; ++i) {
    var overrides = arguments[i]
    if (typeof overrides === 'object') {
      var keys = Object.keys(overrides)
      for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
        var k = keys[j]
        if (overrides[k] !== undefined) {
          target[k] = overrides[k]
        }
      }
    }
  }
  return target
}
 
 
var debug
Iif (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
  debug = function() {
    var args = Array.prototype.slice.call(arguments)
    if (typeof args[0] === 'string') {
      args[0] = 'TUNNEL: ' + args[0]
    } else {
      args.unshift('TUNNEL:')
    }
    console.error.apply(console, args)
  }
} else {
  debug = function() {}
}
exports.debug = debug // for test
 
 
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/semver/

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/semver/

Statements: 27.65% (185 / 669)      Branches: 3.26% (12 / 368)      Functions: 1.23% (1 / 81)      Lines: 28.07% (185 / 659)      Ignored: none     

All files » node-npmtest-sinopia/sinopia/node_modules/semver/
File Statements Branches Functions Lines
semver.js 27.65% (185 / 669) 3.26% (12 / 368) 1.23% (1 / 81) 28.07% (185 / 659)
Code coverage report for node-npmtest-sinopia/sinopia/node_modules/semver/semver.js

npmtest-sinopia (v0.0.1)

Code coverage report for node-npmtest-sinopia/sinopia/node_modules/semver/semver.js

Statements: 27.65% (185 / 669)      Branches: 3.26% (12 / 368)      Functions: 1.23% (1 / 81)      Lines: 28.07% (185 / 659)      Ignored: none     

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207  1 1     1 1                   1       1   1 1     1 1 1               1 1 1 1             1 1           1 1       1 1             1 1     1 1               1 1     1 1           1 1           1 1                         1 1       1         1       1 1   1 1         1 1 1 1   1 1             1 1             1 1 1 1       1 1   1 1 1 1   1 1 1 1       1 1   1 1 1 1   1 1 1 1     1 1 1 1         1 1       1 1             1 1         1 1           1 1       1 34 34 31     1 1                                         1 1           1 1         1   1                                                                                                               1             1       1       1               1                 1                                                               1                                                                                                                                                                                             1 1                         1 1                                                   1   1 1                               1 1       1 1       1 1       1 1       1 1       1 1       1 1       1 1           1 1           1 1       1 1       1 1       1 1       1 1       1 1       1 1                                               1 1                                             1 1                                   1       1       1                         1 1                                                 1       1             1       1                                                                                   1 1                     1                         1                   1           1                                                                     1           1                                                                                                 1             1                                                                                                                                   1                     1                                                         1                           1                                                                 1 1                 1 1               1 1                     1 1         1 1       1 1                                                                                                                                           1      
// export the class if we are in a Node-like system.
Eif (typeof module === 'object' && module.exports === exports)
  exports = module.exports = SemVer;
 
// The debug function is excluded entirely from the minified version.
/* nomin */ var debug;
/* nomin */ Iif (typeof process === 'object' &&
    /* nomin */ process.env &&
    /* nomin */ process.env.NODE_DEBUG &&
    /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG))
  /* nomin */ debug = function() {
    /* nomin */ var args = Array.prototype.slice.call(arguments, 0);
    /* nomin */ args.unshift('SEMVER');
    /* nomin */ console.log.apply(console, args);
    /* nomin */ };
/* nomin */ else
  /* nomin */ debug = function() {};
 
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
exports.SEMVER_SPEC_VERSION = '2.0.0';
 
var MAX_LENGTH = 256;
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
 
// The actual regexps go on exports.re
var re = exports.re = [];
var src = exports.src = [];
var R = 0;
 
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
 
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
 
var NUMERICIDENTIFIER = R++;
src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
var NUMERICIDENTIFIERLOOSE = R++;
src[NUMERICIDENTIFIERLOOSE] = '[0-9]+';
 
 
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
 
var NONNUMERICIDENTIFIER = R++;
src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*';
 
 
// ## Main Version
// Three dot-separated numeric identifiers.
 
var MAINVERSION = R++;
src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[NUMERICIDENTIFIER] + ')';
 
var MAINVERSIONLOOSE = R++;
src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[NUMERICIDENTIFIERLOOSE] + ')';
 
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
 
var PRERELEASEIDENTIFIER = R++;
src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] +
                            '|' + src[NONNUMERICIDENTIFIER] + ')';
 
var PRERELEASEIDENTIFIERLOOSE = R++;
src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] +
                                 '|' + src[NONNUMERICIDENTIFIER] + ')';
 
 
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
 
var PRERELEASE = R++;
src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] +
                  '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
 
var PRERELEASELOOSE = R++;
src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] +
                       '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))';
 
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
 
var BUILDIDENTIFIER = R++;
src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+';
 
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
 
var BUILD = R++;
src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] +
             '(?:\\.' + src[BUILDIDENTIFIER] + ')*))';
 
 
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
 
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
 
var FULL = R++;
var FULLPLAIN = 'v?' + src[MAINVERSION] +
                src[PRERELEASE] + '?' +
                src[BUILD] + '?';
 
src[FULL] = '^' + FULLPLAIN + '$';
 
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] +
                 src[PRERELEASELOOSE] + '?' +
                 src[BUILD] + '?';
 
var LOOSE = R++;
src[LOOSE] = '^' + LOOSEPLAIN + '$';
 
var GTLT = R++;
src[GTLT] = '((?:<|>)?=?)';
 
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
var XRANGEIDENTIFIERLOOSE = R++;
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
var XRANGEIDENTIFIER = R++;
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
 
var XRANGEPLAIN = R++;
src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' +
                   '(?:' + src[PRERELEASE] + ')?' +
                   src[BUILD] + '?' +
                   ')?)?';
 
var XRANGEPLAINLOOSE = R++;
src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:' + src[PRERELEASELOOSE] + ')?' +
                        src[BUILD] + '?' +
                        ')?)?';
 
var XRANGE = R++;
src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
var XRANGELOOSE = R++;
src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$';
 
// Tilde ranges.
// Meaning is "reasonably at or greater than"
var LONETILDE = R++;
src[LONETILDE] = '(?:~>?)';
 
var TILDETRIM = R++;
src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
var tildeTrimReplace = '$1~';
 
var TILDE = R++;
src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
var TILDELOOSE = R++;
src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$';
 
// Caret ranges.
// Meaning is "at least and backwards compatible with"
var LONECARET = R++;
src[LONECARET] = '(?:\\^)';
 
var CARETTRIM = R++;
src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
var caretTrimReplace = '$1^';
 
var CARET = R++;
src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
var CARETLOOSE = R++;
src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$';
 
// A simple gt/lt/eq thing, or just "" to indicate "any version"
var COMPARATORLOOSE = R++;
src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
var COMPARATOR = R++;
src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$';
 
 
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
var COMPARATORTRIM = R++;
src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] +
                      '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')';
 
// this one has to use the /g flag
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
var comparatorTrimReplace = '$1$2$3';
 
 
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
var HYPHENRANGE = R++;
src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' +
                   '\\s+-\\s+' +
                   '(' + src[XRANGEPLAIN] + ')' +
                   '\\s*$';
 
var HYPHENRANGELOOSE = R++;
src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' +
                        '\\s+-\\s+' +
                        '(' + src[XRANGEPLAINLOOSE] + ')' +
                        '\\s*$';
 
// Star ranges basically just allow anything at all.
var STAR = R++;
src[STAR] = '(<|>)?=?\\s*\\*';
 
// Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
for (var i = 0; i < R; i++) {
  debug(i, src[i]);
  if (!re[i])
    re[i] = new RegExp(src[i]);
}
 
exports.parse = parse;
function parse(version, loose) {
  if (version instanceof SemVer)
    return version;
 
  if (typeof version !== 'string')
    return null;
 
  if (version.length > MAX_LENGTH)
    return null;
 
  var r = loose ? re[LOOSE] : re[FULL];
  if (!r.test(version))
    return null;
 
  try {
    return new SemVer(version, loose);
  } catch (er) {
    return null;
  }
}
 
exports.valid = valid;
function valid(version, loose) {
  var v = parse(version, loose);
  return v ? v.version : null;
}
 
 
exports.clean = clean;
function clean(version, loose) {
  var s = parse(version.trim().replace(/^[=v]+/, ''), loose);
  return s ? s.version : null;
}
 
exports.SemVer = SemVer;
 
function SemVer(version, loose) {
  if (version instanceof SemVer) {
    if (version.loose === loose)
      return version;
    else
      version = version.version;
  } else if (typeof version !== 'string') {
    throw new TypeError('Invalid Version: ' + version);
  }
 
  if (version.length > MAX_LENGTH)
    throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
 
  if (!(this instanceof SemVer))
    return new SemVer(version, loose);
 
  debug('SemVer', version, loose);
  this.loose = loose;
  var m = version.trim().match(loose ? re[LOOSE] : re[FULL]);
 
  if (!m)
    throw new TypeError('Invalid Version: ' + version);
 
  this.raw = version;
 
  // these are actually numbers
  this.major = +m[1];
  this.minor = +m[2];
  this.patch = +m[3];
 
  if (this.major > MAX_SAFE_INTEGER || this.major < 0)
    throw new TypeError('Invalid major version')
 
  if (this.minor > MAX_SAFE_INTEGER || this.minor < 0)
    throw new TypeError('Invalid minor version')
 
  if (this.patch > MAX_SAFE_INTEGER || this.patch < 0)
    throw new TypeError('Invalid patch version')
 
  // numberify any prerelease numeric ids
  if (!m[4])
    this.prerelease = [];
  else
    this.prerelease = m[4].split('.').map(function(id) {
      if (/^[0-9]+$/.test(id)) {
        var num = +id
        if (num >= 0 && num < MAX_SAFE_INTEGER)
          return num
      }
      return id;
    });
 
  this.build = m[5] ? m[5].split('.') : [];
  this.format();
}
 
SemVer.prototype.format = function() {
  this.version = this.major + '.' + this.minor + '.' + this.patch;
  if (this.prerelease.length)
    this.version += '-' + this.prerelease.join('.');
  return this.version;
};
 
SemVer.prototype.inspect = function() {
  return '<SemVer "' + this + '">';
};
 
SemVer.prototype.toString = function() {
  return this.version;
};
 
SemVer.prototype.compare = function(other) {
  debug('SemVer.compare', this.version, this.loose, other);
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.loose);
 
  return this.compareMain(other) || this.comparePre(other);
};
 
SemVer.prototype.compareMain = function(other) {
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.loose);
 
  return compareIdentifiers(this.major, other.major) ||
         compareIdentifiers(this.minor, other.minor) ||
         compareIdentifiers(this.patch, other.patch);
};
 
SemVer.prototype.comparePre = function(other) {
  if (!(other instanceof SemVer))
    other = new SemVer(other, this.loose);
 
  // NOT having a prerelease is > having one
  if (this.prerelease.length && !other.prerelease.length)
    return -1;
  else if (!this.prerelease.length && other.prerelease.length)
    return 1;
  else if (!this.prerelease.length && !other.prerelease.length)
    return 0;
 
  var i = 0;
  do {
    var a = this.prerelease[i];
    var b = other.prerelease[i];
    debug('prerelease compare', i, a, b);
    if (a === undefined && b === undefined)
      return 0;
    else if (b === undefined)
      return 1;
    else if (a === undefined)
      return -1;
    else if (a === b)
      continue;
    else
      return compareIdentifiers(a, b);
  } while (++i);
};
 
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
SemVer.prototype.inc = function(release, identifier) {
  switch (release) {
    case 'premajor':
      this.prerelease.length = 0;
      this.patch = 0;
      this.minor = 0;
      this.major++;
      this.inc('pre', identifier);
      break;
    case 'preminor':
      this.prerelease.length = 0;
      this.patch = 0;
      this.minor++;
      this.inc('pre', identifier);
      break;
    case 'prepatch':
      // If this is already a prerelease, it will bump to the next version
      // drop any prereleases that might already exist, since they are not
      // relevant at this point.
      this.prerelease.length = 0;
      this.inc('patch', identifier);
      this.inc('pre', identifier);
      break;
    // If the input is a non-prerelease version, this acts the same as
    // prepatch.
    case 'prerelease':
      if (this.prerelease.length === 0)
        this.inc('patch', identifier);
      this.inc('pre', identifier);
      break;
 
    case 'major':
      // If this is a pre-major version, bump up to the same major version.
      // Otherwise increment major.
      // 1.0.0-5 bumps to 1.0.0
      // 1.1.0 bumps to 2.0.0
      if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0)
        this.major++;
      this.minor = 0;
      this.patch = 0;
      this.prerelease = [];
      break;
    case 'minor':
      // If this is a pre-minor version, bump up to the same minor version.
      // Otherwise increment minor.
      // 1.2.0-5 bumps to 1.2.0
      // 1.2.1 bumps to 1.3.0
      if (this.patch !== 0 || this.prerelease.length === 0)
        this.minor++;
      this.patch = 0;
      this.prerelease = [];
      break;
    case 'patch':
      // If this is not a pre-release version, it will increment the patch.
      // If it is a pre-release it will bump up to the same patch version.
      // 1.2.0-5 patches to 1.2.0
      // 1.2.0 patches to 1.2.1
      if (this.prerelease.length === 0)
        this.patch++;
      this.prerelease = [];
      break;
    // This probably shouldn't be used publicly.
    // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
    case 'pre':
      if (this.prerelease.length === 0)
        this.prerelease = [0];
      else {
        var i = this.prerelease.length;
        while (--i >= 0) {
          if (typeof this.prerelease[i] === 'number') {
            this.prerelease[i]++;
            i = -2;
          }
        }
        if (i === -1) // didn't increment anything
          this.prerelease.push(0);
      }
      if (identifier) {
        // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
        // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
        if (this.prerelease[0] === identifier) {
          if (isNaN(this.prerelease[1]))
            this.prerelease = [identifier, 0];
        } else
          this.prerelease = [identifier, 0];
      }
      break;
 
    default:
      throw new Error('invalid increment argument: ' + release);
  }
  this.format();
  return this;
};
 
exports.inc = inc;
function inc(version, release, loose, identifier) {
  if (typeof(loose) === 'string') {
    identifier = loose;
    loose = undefined;
  }
 
  try {
    return new SemVer(version, loose).inc(release, identifier).version;
  } catch (er) {
    return null;
  }
}
 
exports.diff = diff;
function diff(version1, version2) {
  if (eq(version1, version2)) {
    return null;
  } else {
    var v1 = parse(version1);
    var v2 = parse(version2);
    if (v1.prerelease.length || v2.prerelease.length) {
      for (var key in v1) {
        if (key === 'major' || key === 'minor' || key === 'patch') {
          if (v1[key] !== v2[key]) {
            return 'pre'+key;
          }
        }
      }
      return 'prerelease';
    }
    for (var key in v1) {
      if (key === 'major' || key === 'minor' || key === 'patch') {
        if (v1[key] !== v2[key]) {
          return key;
        }
      }
    }
  }
}
 
exports.compareIdentifiers = compareIdentifiers;
 
var numeric = /^[0-9]+$/;
function compareIdentifiers(a, b) {
  var anum = numeric.test(a);
  var bnum = numeric.test(b);
 
  if (anum && bnum) {
    a = +a;
    b = +b;
  }
 
  return (anum && !bnum) ? -1 :
         (bnum && !anum) ? 1 :
         a < b ? -1 :
         a > b ? 1 :
         0;
}
 
exports.rcompareIdentifiers = rcompareIdentifiers;
function rcompareIdentifiers(a, b) {
  return compareIdentifiers(b, a);
}
 
exports.major = major;
function major(a, loose) {
  return new SemVer(a, loose).major;
}
 
exports.minor = minor;
function minor(a, loose) {
  return new SemVer(a, loose).minor;
}
 
exports.patch = patch;
function patch(a, loose) {
  return new SemVer(a, loose).patch;
}
 
exports.compare = compare;
function compare(a, b, loose) {
  return new SemVer(a, loose).compare(b);
}
 
exports.compareLoose = compareLoose;
function compareLoose(a, b) {
  return compare(a, b, true);
}
 
exports.rcompare = rcompare;
function rcompare(a, b, loose) {
  return compare(b, a, loose);
}
 
exports.sort = sort;
function sort(list, loose) {
  return list.sort(function(a, b) {
    return exports.compare(a, b, loose);
  });
}
 
exports.rsort = rsort;
function rsort(list, loose) {
  return list.sort(function(a, b) {
    return exports.rcompare(a, b, loose);
  });
}
 
exports.gt = gt;
function gt(a, b, loose) {
  return compare(a, b, loose) > 0;
}
 
exports.lt = lt;
function lt(a, b, loose) {
  return compare(a, b, loose) < 0;
}
 
exports.eq = eq;
function eq(a, b, loose) {
  return compare(a, b, loose) === 0;
}
 
exports.neq = neq;
function neq(a, b, loose) {
  return compare(a, b, loose) !== 0;
}
 
exports.gte = gte;
function gte(a, b, loose) {
  return compare(a, b, loose) >= 0;
}
 
exports.lte = lte;
function lte(a, b, loose) {
  return compare(a, b, loose) <= 0;
}
 
exports.cmp = cmp;
function cmp(a, op, b, loose) {
  var ret;
  switch (op) {
    case '===':
      if (typeof a === 'object') a = a.version;
      if (typeof b === 'object') b = b.version;
      ret = a === b;
      break;
    case '!==':
      if (typeof a === 'object') a = a.version;
      if (typeof b === 'object') b = b.version;
      ret = a !== b;
      break;
    case '': case '=': case '==': ret = eq(a, b, loose); break;
    case '!=': ret = neq(a, b, loose); break;
    case '>': ret = gt(a, b, loose); break;
    case '>=': ret = gte(a, b, loose); break;
    case '<': ret = lt(a, b, loose); break;
    case '<=': ret = lte(a, b, loose); break;
    default: throw new TypeError('Invalid operator: ' + op);
  }
  return ret;
}
 
exports.Comparator = Comparator;
function Comparator(comp, loose) {
  if (comp instanceof Comparator) {
    if (comp.loose === loose)
      return comp;
    else
      comp = comp.value;
  }
 
  if (!(this instanceof Comparator))
    return new Comparator(comp, loose);
 
  debug('comparator', comp, loose);
  this.loose = loose;
  this.parse(comp);
 
  if (this.semver === ANY)
    this.value = '';
  else
    this.value = this.operator + this.semver.version;
 
  debug('comp', this);
}
 
var ANY = {};
Comparator.prototype.parse = function(comp) {
  var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
  var m = comp.match(r);
 
  if (!m)
    throw new TypeError('Invalid comparator: ' + comp);
 
  this.operator = m[1];
  if (this.operator === '=')
    this.operator = '';
 
  // if it literally is just '>' or '' then allow anything.
  if (!m[2])
    this.semver = ANY;
  else
    this.semver = new SemVer(m[2], this.loose);
};
 
Comparator.prototype.inspect = function() {
  return '<SemVer Comparator "' + this + '">';
};
 
Comparator.prototype.toString = function() {
  return this.value;
};
 
Comparator.prototype.test = function(version) {
  debug('Comparator.test', version, this.loose);
 
  if (this.semver === ANY)
    return true;
 
  if (typeof version === 'string')
    version = new SemVer(version, this.loose);
 
  return cmp(version, this.operator, this.semver, this.loose);
};
 
 
exports.Range = Range;
function Range(range, loose) {
  if ((range instanceof Range) && range.loose === loose)
    return range;
 
  if (!(this instanceof Range))
    return new Range(range, loose);
 
  this.loose = loose;
 
  // First, split based on boolean or ||
  this.raw = range;
  this.set = range.split(/\s*\|\|\s*/).map(function(range) {
    return this.parseRange(range.trim());
  }, this).filter(function(c) {
    // throw out any that are not relevant for whatever reason
    return c.length;
  });
 
  if (!this.set.length) {
    throw new TypeError('Invalid SemVer Range: ' + range);
  }
 
  this.format();
}
 
Range.prototype.inspect = function() {
  return '<SemVer Range "' + this.range + '">';
};
 
Range.prototype.format = function() {
  this.range = this.set.map(function(comps) {
    return comps.join(' ').trim();
  }).join('||').trim();
  return this.range;
};
 
Range.prototype.toString = function() {
  return this.range;
};
 
Range.prototype.parseRange = function(range) {
  var loose = this.loose;
  range = range.trim();
  debug('range', range, loose);
  // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
  var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
  range = range.replace(hr, hyphenReplace);
  debug('hyphen replace', range);
  // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
  range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
  debug('comparator trim', range, re[COMPARATORTRIM]);
 
  // `~ 1.2.3` => `~1.2.3`
  range = range.replace(re[TILDETRIM], tildeTrimReplace);
 
  // `^ 1.2.3` => `^1.2.3`
  range = range.replace(re[CARETTRIM], caretTrimReplace);
 
  // normalize spaces
  range = range.split(/\s+/).join(' ');
 
  // At this point, the range is completely trimmed and
  // ready to be split into comparators.
 
  var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
  var set = range.split(' ').map(function(comp) {
    return parseComparator(comp, loose);
  }).join(' ').split(/\s+/);
  if (this.loose) {
    // in loose mode, throw out any that are not valid comparators
    set = set.filter(function(comp) {
      return !!comp.match(compRe);
    });
  }
  set = set.map(function(comp) {
    return new Comparator(comp, loose);
  });
 
  return set;
};
 
// Mostly just for testing and legacy API reasons
exports.toComparators = toComparators;
function toComparators(range, loose) {
  return new Range(range, loose).set.map(function(comp) {
    return comp.map(function(c) {
      return c.value;
    }).join(' ').trim().split(' ');
  });
}
 
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
function parseComparator(comp, loose) {
  debug('comp', comp);
  comp = replaceCarets(comp, loose);
  debug('caret', comp);
  comp = replaceTildes(comp, loose);
  debug('tildes', comp);
  comp = replaceXRanges(comp, loose);
  debug('xrange', comp);
  comp = replaceStars(comp, loose);
  debug('stars', comp);
  return comp;
}
 
function isX(id) {
  return !id || id.toLowerCase() === 'x' || id === '*';
}
 
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
function replaceTildes(comp, loose) {
  return comp.trim().split(/\s+/).map(function(comp) {
    return replaceTilde(comp, loose);
  }).join(' ');
}
 
function replaceTilde(comp, loose) {
  var r = loose ? re[TILDELOOSE] : re[TILDE];
  return comp.replace(r, function(_, M, m, p, pr) {
    debug('tilde', comp, _, M, m, p, pr);
    var ret;
 
    if (isX(M))
      ret = '';
    else if (isX(m))
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    else if (isX(p))
      // ~1.2 == >=1.2.0- <1.3.0-
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
    else if (pr) {
      debug('replaceTilde pr', pr);
      if (pr.charAt(0) !== '-')
        pr = '-' + pr;
      ret = '>=' + M + '.' + m + '.' + p + pr +
            ' <' + M + '.' + (+m + 1) + '.0';
    } else
      // ~1.2.3 == >=1.2.3 <1.3.0
      ret = '>=' + M + '.' + m + '.' + p +
            ' <' + M + '.' + (+m + 1) + '.0';
 
    debug('tilde return', ret);
    return ret;
  });
}
 
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
// ^1.2.3 --> >=1.2.3 <2.0.0
// ^1.2.0 --> >=1.2.0 <2.0.0
function replaceCarets(comp, loose) {
  return comp.trim().split(/\s+/).map(function(comp) {
    return replaceCaret(comp, loose);
  }).join(' ');
}
 
function replaceCaret(comp, loose) {
  debug('caret', comp, loose);
  var r = loose ? re[CARETLOOSE] : re[CARET];
  return comp.replace(r, function(_, M, m, p, pr) {
    debug('caret', comp, _, M, m, p, pr);
    var ret;
 
    if (isX(M))
      ret = '';
    else if (isX(m))
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    else if (isX(p)) {
      if (M === '0')
        ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
      else
        ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
    } else if (pr) {
      debug('replaceCaret pr', pr);
      if (pr.charAt(0) !== '-')
        pr = '-' + pr;
      if (M === '0') {
        if (m === '0')
          ret = '>=' + M + '.' + m + '.' + p + pr +
                ' <' + M + '.' + m + '.' + (+p + 1);
        else
          ret = '>=' + M + '.' + m + '.' + p + pr +
                ' <' + M + '.' + (+m + 1) + '.0';
      } else
        ret = '>=' + M + '.' + m + '.' + p + pr +
              ' <' + (+M + 1) + '.0.0';
    } else {
      debug('no pr');
      if (M === '0') {
        if (m === '0')
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + m + '.' + (+p + 1);
        else
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + (+m + 1) + '.0';
      } else
        ret = '>=' + M + '.' + m + '.' + p +
              ' <' + (+M + 1) + '.0.0';
    }
 
    debug('caret return', ret);
    return ret;
  });
}
 
function replaceXRanges(comp, loose) {
  debug('replaceXRanges', comp, loose);
  return comp.split(/\s+/).map(function(comp) {
    return replaceXRange(comp, loose);
  }).join(' ');
}
 
function replaceXRange(comp, loose) {
  comp = comp.trim();
  var r = loose ? re[XRANGELOOSE] : re[XRANGE];
  return comp.replace(r, function(ret, gtlt, M, m, p, pr) {
    debug('xRange', comp, ret, gtlt, M, m, p, pr);
    var xM = isX(M);
    var xm = xM || isX(m);
    var xp = xm || isX(p);
    var anyX = xp;
 
    if (gtlt === '=' && anyX)
      gtlt = '';
 
    if (xM) {
      if (gtlt === '>' || gtlt === '<') {
        // nothing is allowed
        ret = '<0.0.0';
      } else {
        // nothing is forbidden
        ret = '*';
      }
    } else if (gtlt && anyX) {
      // replace X with 0
      if (xm)
        m = 0;
      if (xp)
        p = 0;
 
      if (gtlt === '>') {
        // >1 => >=2.0.0
        // >1.2 => >=1.3.0
        // >1.2.3 => >= 1.2.4
        gtlt = '>=';
        if (xm) {
          M = +M + 1;
          m = 0;
          p = 0;
        } else if (xp) {
          m = +m + 1;
          p = 0;
        }
      } else if (gtlt === '<=') {
        // <=0.7.x is actually <0.8.0, since any 0.7.x should
        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
        gtlt = '<'
        if (xm)
          M = +M + 1
        else
          m = +m + 1
      }
 
      ret = gtlt + M + '.' + m + '.' + p;
    } else if (xm) {
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
    } else if (xp) {
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
    }
 
    debug('xRange return', ret);
 
    return ret;
  });
}
 
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
function replaceStars(comp, loose) {
  debug('replaceStars', comp, loose);
  // Looseness is ignored here.  star is always as loose as it gets!
  return comp.trim().replace(re[STAR], '');
}
 
// This function is passed to string.replace(re[HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0
function hyphenReplace($0,
                       from, fM, fm, fp, fpr, fb,
                       to, tM, tm, tp, tpr, tb) {
 
  if (isX(fM))
    from = '';
  else if (isX(fm))
    from = '>=' + fM + '.0.0';
  else if (isX(fp))
    from = '>=' + fM + '.' + fm + '.0';
  else
    from = '>=' + from;
 
  if (isX(tM))
    to = '';
  else if (isX(tm))
    to = '<' + (+tM + 1) + '.0.0';
  else if (isX(tp))
    to = '<' + tM + '.' + (+tm + 1) + '.0';
  else if (tpr)
    to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
  else
    to = '<=' + to;
 
  return (from + ' ' + to).trim();
}
 
 
// if ANY of the sets match ALL of its comparators, then pass
Range.prototype.test = function(version) {
  if (!version)
    return false;
 
  if (typeof version === 'string')
    version = new SemVer(version, this.loose);
 
  for (var i = 0; i < this.set.length; i++) {
    if (testSet(this.set[i], version))
      return true;
  }
  return false;
};
 
function testSet(set, version) {
  for (var i = 0; i < set.length; i++) {
    if (!set[i].test(version))
      return false;
  }
 
  if (version.prerelease.length) {
    // Find the set of versions that are allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (var i = 0; i < set.length; i++) {
      debug(set[i].semver);
      if (set[i].semver === ANY)
        continue;
 
      if (set[i].semver.prerelease.length > 0) {
        var allowed = set[i].semver;
        if (allowed.major === version.major &&
            allowed.minor === version.minor &&
            allowed.patch === version.patch)
          return true;
      }
    }
 
    // Version has a -pre, but it's not one of the ones we like.
    return false;
  }
 
  return true;
}
 
exports.satisfies = satisfies;
function satisfies(version, range, loose) {
  try {
    range = new Range(range, loose);
  } catch (er) {
    return false;
  }
  return range.test(version);
}
 
exports.maxSatisfying = maxSatisfying;
function maxSatisfying(versions, range, loose) {
  return versions.filter(function(version) {
    return satisfies(version, range, loose);
  }).sort(function(a, b) {
    return rcompare(a, b, loose);
  })[0] || null;
}
 
exports.validRange = validRange;
function validRange(range, loose) {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, loose).range || '*';
  } catch (er) {
    return null;
  }
}
 
// Determine if version is less than all the versions possible in the range
exports.ltr = ltr;
function ltr(version, range, loose) {
  return outside(version, range, '<', loose);
}
 
// Determine if version is greater than all the versions possible in the range.
exports.gtr = gtr;
function gtr(version, range, loose) {
  return outside(version, range, '>', loose);
}
 
exports.outside = outside;
function outside(version, range, hilo, loose) {
  version = new SemVer(version, loose);
  range = new Range(range, loose);
 
  var gtfn, ltefn, ltfn, comp, ecomp;
  switch (hilo) {
    case '>':
      gtfn = gt;
      ltefn = lte;
      ltfn = lt;
      comp = '>';
      ecomp = '>=';
      break;
    case '<':
      gtfn = lt;
      ltefn = gte;
      ltfn = gt;
      comp = '<';
      ecomp = '<=';
      break;
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"');
  }
 
  // If it satisifes the range it is not outside
  if (satisfies(version, range, loose)) {
    return false;
  }
 
  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.
 
  for (var i = 0; i < range.set.length; ++i) {
    var comparators = range.set[i];
 
    var high = null;
    var low = null;
 
    comparators.forEach(function(comparator) {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator;
      low = low || comparator;
      if (gtfn(comparator.semver, high.semver, loose)) {
        high = comparator;
      } else if (ltfn(comparator.semver, low.semver, loose)) {
        low = comparator;
      }
    });
 
    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false;
    }
 
    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false;
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false;
    }
  }
  return true;
}
 
// Use the define() function if we're in AMD land
Iif (typeof define === 'function' && define.amd)
  define(exports);